Basic Concepts

Advanced Programming

SUT • Spring 2019

Review

  • Variables

    • Primitive data types

  • Operators

  • Methods

    • Parameter passing

    • Call by value

  • Conditions

    • If, else, else if

  • Loops

    • while

    • do-while

    • for

Outline

  • Review

  • User input

    • Scanner

  • Strong type checking

  • Other flow-control structures

    • switch

    • break & continue

  • Strings

  • Arrays

User input

User input

  • Print on console

    • System.out.println

  • How to read from console?

    • Scanner

import java.util.Scanner;

public class UserInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        double d = scanner.nextDouble();
    }

    public static void power() {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        long pow = (long)Math.pow(a, b);
        System.out.println(pow);
    }
}

Type Checking

Type Checking

  • Java has a strong type-checking mechanism

  • Some assignment is not permitted

public class TypeChecking{
  public static void main(String[] args){
    int intVal = 2;
    long longVal =12;

    // intVal = longVal; // Syntax Error
    longVal = intVal; // OK
    intVal = (int)longVal; // OK (Type Casting)
  }
}

Direct Type Conversion

  • The arrows are transitive

  • All other conversions need an explicit cast

  • boolean is not convertible

  • char is a special type

short

byte

char

int

long

float

double

boolean

Type Conversion Grid

From boolean byte short char int long float double
boolean - N N N N N N N
byte N - Y C Y Y Y Y
short N C - C Y Y Y Y
char N C C - Y Y Y Y
int N C C C - Y Y* Y
long N C C C C - Y* Y*
float N C C C C C - Y
double N C C C C C C -

Type Conversion

  • N : the conversion cannot be performed

  • Y : the conversion is performed automatically and implicitly by Java

  • C : the conversion is a narrowing conversion and requires an explicit cast

  • Y* : the conversion is an automatic widening conversion, but that some of the least significant digits of the value may be lost by the conversion

Example

  • floating-point types are approximations of numbers

  • They cannot always hold as many significant digits as the integer types

public class TypeConversion {
    public static void main(String[] args) {
        int i = 123456789; //a big integer
        double f = i; //f stores and approximation of i
        System.out.println(f);//output : 1.23456792E8
        i = (int) f;
        System.out.println(i); //output : 123456792
    }
}

Floating Point, Some Notes

  • Double.NaN

  • Infinity

    • Negative infinity

  • Formatting a double

public class FloatingPoint{
  public static void main(String[] args){
    double nan = 0.0 / 0.0;
    double pinf = Double.MAX_VALUE * 2;
    double ninf = Double.MAX_VALUE * (-2);
    System.out.println(Double.NEGATIVE_INFINITY);
    System.out.println(Double.POSITIVE_INFINITY);
    System.out.format("min double = %.2f", 12.216213);
  }
}

Comparison

  • Compare doubles

  • Using == with float or double is an anti-pattern

  • An infinite loop:

public class InfiniteLoop{
  public static void main(String[] args){
    for (float f = 0f; f != 10f; f += 0.1){
      System.out.println(f);
    }
  }
}

Numeric Assignments

  • Numeric Suffix

  • Assignment Overflow

    • Large long to int

      • Lower bits are used

      • No runtime error

    • Large double to integer

      • Brings a max int

public class NumericSuffix{
  public static void main(String[] args){
    Double d = 123.54d;
    Float f = 123f;
    Long l = 123123l;
    byte b = 127; // Nothing
  }
}

Switch Statement

  • An alternative to if-else

  • Better structure

  • Before Java 1.7

    • When the condition is a numeric or an ordinal variable

  • With Java 1.7

    • Strings are also allowed

Switch Example

import java.util.Scanner;

public class Switch {
    public static void main(String[] args) {
        int j = 1;
        switch (j) {
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
                break;
            default:
                System.out.println("default");
        }
    }
}

Switch Example

import java.util.Scanner;

public class Switch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean again = true;
        while (again) {
            System.out.println("1: Play");
            System.out.println("2: Setting:");
            System.out.println("3: Exit");
            System.out.print("Enter Your Choice:");
            int i = scanner.nextInt();
            switch (i) {
                case 1:
                    // play();
                    break;
                case 2:
                    // setting();
                    break;
                case 3:
                    again = false;
                    break;
                default:
                    System.out.println("Enter a valid number");
            }
        }
    }
}

Break

  • Breaks the execution of a loop

import java.util.Scanner;

public class ControlLoop {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            int nextInt = scanner.nextInt();
            if (nextInt == 0)
                break;
        }
    }
}

Continue

  • Stops the execution of the body of the loop and continues from the beginning of the loop

  • Difference between continue in for and while

import java.util.Scanner;

public class ControlLoop {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i == 4)
                continue;
            System.out.println(i);
        }
    }
}

Nested Loops

  • How to break or continue from outer loop?
import java.util.Scanner;

public class ControlLoop {
    public static void main(String[] args) {
        int nextInt;
        do {
            nextInt = scanner.nextInt();
            for (int i = 0; i < nextInt; i++) {
                System.out.println(i);
            }
        } while (nextInt > 0);
    }
}

Label

import java.util.Scanner;

public class ControlLoop {
    public static void main(String[] args) {
        outer:
        for (int i = 0; i < 10; i++) {
            inner:
            for (int j = 0; j < 10; j++) {
                if (j == 2)
                    break outer;
                else {
                    System.out.println(i);
                    System.out.println(j);
                    continue inner;
                }
            }
        }
    }
}

Tip of the Day: Indentation

import java.util.Scanner;

public class Indentation {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int nextInt;
        do{
        nextInt=scanner.nextInt();
        for(int i=0; i<nextInt; i++){
        System.out.println(i);
        }
        }while(nextInt>0);
    }
}

Tip of the Day: Indentation

import java.util.Scanner;

public class Indentation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int nextInt;
        do {
            nextInt = scanner.nextInt();
            for (int i = 0; i < nextInt; i++) {
                System.out.println(i);
            }
        } while (nextInt > 0);
    }
}

Comments

import java.util.Scanner;

public class Indentation {
    public static void main(String[] args) {        
        // nextInt = scanner.nextInt();

        /*
        nextInt = scanner.nextInt();
        for(int i=0;i<nextInt;i++){
                System.out.println(i);
        }
        */

        /**
         * ... text ...
         */
    }
}
  • Comments are ignored by compiler

  • One-line comment

  • Multiple-line comment

  • Javadoc comments

Example

import java.util.Scanner;

public class Comment {
    /**
     * @author Ali Alavi
     * If the input is a prime number, it returns true
     */
    public boolean isPrime(int number) {
        if (number < 1)
            return false;
          /*if(isEven(number))
            return false;
          */
        for (int i = 2; i < number / 2; i++) //searching for a divisible
            if (number % i == 0)
                return false;
        return true;
    }
}

String

Contents

  • A sequence of characters

  • Character

  • Strings

  • String is not a primitive type

import java.util.Scanner;

public class StringExample {
    public static void main(String[] args) {
        char ch;
        ch = 'a';
        ch = '1';
        ch = '#';

        String st;
        st = "Ali";
        st = "123";
        st = "1";
        st = "";
    }
}

String

  • String in C and C++

    • char* and char[]

    • \0 at the end of String

  • Some functions

    • strlen, strcpy, …

  • String in java is String in java is a class

  • not equal to char[]

  • Constant strings

    • “salam!”

    • “Hellow World!”

Example

import java.util.Scanner;

public class StringExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input;
        input = scanner.next();
        switch (input) {
            case "Salam":
                System.out.println("Hi!");
                break;
            case "Khdahafez":
                System.out.println("Bye!");
                break;
            default:
                System.out.println("Ha?!");
                break;
        }
        System.out.println(input);
    }
}

Example

import java.util.Scanner;

public class StringExample {
    public static void main(String[] args) {
        String input = "Nader and Simin, A Separation";
        char ch = input.charAt(0);
        int i = input.indexOf("Nader");
        int j = input.lastIndexOf("Simin");
        String newS = input.replace("Separation", "Reconciliation");
        String sth = newS + ch + i + j;
        System.out.println(sth);
    }
}

String Methods

  • charAt

  • concat:  plus (+) operator

  • contains

  • startsWith

  • endsWith

  • indesxOf: first index of sth

  • lastIndexOf    

  • replace

  • substring

  • length

  • split

  • Regular Expression or Regex

  • Regex is a way to describe a set of strings

  • Based on their common characteristics

  • Regex can be used to search, edit, or manipulate text

  • You must learn a specific syntax to create regex

Regex Examples

Regex Meaning Ex .1 Ex .2 Ex .3
Salam Salam Salam
\d A digit 4 5 9
. Any character 2 A #
[afg] a or f or g a f g
[a-zA-Z] Range: a through z or A through Z, inclusive A a m
Salam|bye Salam or bye Salam bye
a+ One or more a aaaaa aa a
[a-z]+[\d]* a lowercase string and an optional integer number ali ali24 a43

String and Regex

public class Regex {
    public static void main(String[] args) {
        String input = "Nader and Simin";

        boolean noDigitString = input.matches("[\\D]+");

        System.out.println(noDigitString);
        String[] array = input.split("[ ,]");
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
    }
}

Regex Usage

public class Regex {
    public static void main(String[] args) {
        String input = "Nader and Simin, A Separation.";
        input = input.replace(".", "*");
        //input = Nader and Simin, A Separation*

        input = input.replaceAll(".", "*");
        //i
   }
}

Immutable String

  • String in java is an immutable class

  • After creating a string, you can not change it

  • If you want to change it, you should create a new string

  • There is no such methods for strings:

    • setCharAt(int)

    • setValue(String)

  • Methods like replace and replaceAll, do not change the value

    • They return a new String

Example

  • What is the output of this code?
public class Regex {
    public static void main(String[] args) {
        String str = "Gholi";
        str.replaceAll("li", "lam");
        System.out.println(str);

        String replaced = str.replaceAll("li", "lam");
        System.out.println(replaced);
    }
}

Data Hierarchy

  • Bit

  • Byte

  • Character

  • Word

Java Characters

  • A Java character has two bytes

  • Java supports Unicode character set standard

    • ASCII

  • Java uses UTF-16 encoding

  • Other unicode encodings:

    • UTF-8

    • UTF-16

  • Other non-unicode encodings

    • Windows-1256

Java Special Characters

  • Some characters are special characters

  • Special characters are shown using backslash

  • Examples:

    • New line: \n

    • Tab : \t

    • Double-quote : \”

    • Single-quote : \’

    • Backslash : \\

Java Special Characters

public class Regex {
    public static void main(String[] args) {
       String s = "Salam!\nI am S\tA";
        System.out.println(s);
        s = "\\ \' \"";
        System.out.println(s);

        /* output:
            Salam!
            I am S	A
            \ ' "
         */
    }
}

Array

Array

  • Collections of related data items

  • related data items of the same type

  • Arrays are fixed-length entities

  • they remain the same length once they are created

  • An array is a group of variables

    • called elements

  • containing values that all have the same type

  • The position number of the element is it’s index

  • Array elements are sequentially located in memory

Array

Example

public class ArrayExample {
    public static void main(String[] args) {
        // Create an array of 10 integer elements
        int[] array = new int[10];
        int array[] = new int[10]; // equal
        
        // Create an array of n characters
        char[] characters = new char[n];
        
        // Change value of 5’th element
        array[5] = 12;
        
        // Retrieving value of n’th element
        char ch = array[n];
    }
}

Example

import java.util.Scanner;

public class ArrayExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        double numbers[] = new double[n];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = scanner.nextDouble();
        }
        for (int i = 0; i < numbers.length; i++) {
            double d = numbers[i];
            System.out.println(d);
        }
    }
}

Array Creation Shortcut

import java.util.Scanner;

public class ArrayExample {
    public static void main(String[] args) {
        char[] array = new char[3];
	array[0]  = 'a';
	array[1]  = 's';
	array[2]  = 't';

        // The above code can be rewritten as:
	char[] array2 = {'a', 's', 't'};

        // Other examples:
        int[] numbers = {1, 2, 3, 5, 9, 123};
        boolean[] b = {true, true, false, true};
    }
}

Multidimensional Arrays

import java.util.Scanner;

public class ArrayExample {
    public static void main(String[] args) {
        int[][] matrix = new int[3][4];
        matrix[2][3] = 2;
        System.out.println(matrix[2][1]);
        
        int[][] matrix = new int[3][];
        matrix[0] = new int[2];
        matrix[1] = new int[5];
        matrix[2] = new int[4];
        matrix[2][3] = 2;
        System.out.println(matrix[2][1]);
        matrix[0][3] = 2; // Runtime Error (ArrayIndexOutOfBoundsException)
    }
}

Passing Arrays to Methods

public class ArrayParameter {
    public static void main(String[] args) {
        int[] array = {1, 2, -4, 0};
        System.out.println(max(array));
    }

    public static int max(int[] numbers) {
        if (numbers == null || numbers.length == 0)
            return -1;
        int max = numbers[0];
        for (int i = 1; i < numbers.length; i++)
            if (max < numbers[i])
                max = numbers[i];
        return max;
    }
}

Multi-Dimensional Array Parameters

int determinant(int[][] matrix){…}
int [][] matrix = { {1,2}, {3,4}} ;  
int de = determinant(matrix);

void check(int[][] array){…}
int [][] unbalanced = { {1,2}, {3,4,5,6,7,8}};  
check(unbalanced);

boolean f(double[][][] cube){…}

Call by Element Values?

  • No

  • If the method has an array parameter

  • Array elements are not copied on method invocations

  • A reference to the array is passed to the method

  • More about this topic later

Exercises

  • Write a method for sorting an array of integers

  • Write a method that compares two arrays

    • returns true if elements of the arrays are equal

    • returns false, otherwise

  • Write a method that returns determinant of a matrix

    • Matrix is a two-dimensional array as the method parameter

Title Text

Basic Concepts

By Behnam Hatami

Basic Concepts

Basic Concepts / Advanced Programming Course @ SUT, Spring 2019

  • 1,452