reading-notes

View on GitHub

Exceptions, primitives, File I/O

Primitives

java primitives and the memory size they take.

They live inside the stack, faster to access

java wrappers classes of primitives, they take more memory

They live inside the heap, slower than primitives access

As mentioned above the Boolean class instance occupies 128 bit which equls to 128 variable of boolean primitive type.

Exceptions

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

The following code that shows the basic operation of calculator(add, sub, multiply, divide) has an exception when divide by zero.

public class ExptionsDemo {
    public static void main(String[] args){
        //this method will cause an exeption 
          showBasicOperations(20,0);
    }

    public static int divide(int a, int b){
        return a / b;
    }
    public static int sum(int a, int b){
        return a + b;
    }
    public static int subtract(int a, int b){
        return a - b;
    }
    public static int multiply(int a, int b){
        return a * b;
    }

    public static void showBasicOperations(int a, int b){
      try{
        System.out.println("a" + "+" + "b = " + sum(a,b));
        System.out.println("a" + "-" + "b = " + subtract(a,b));
        System.out.println("a" + "*" + "b = " + multiply(a,b));
        System.out.println("a" + "/" + "b = " + divide(a,b));
      }catch(Execption e){
          e.printStackTrace();
        } 
    }
}

when the code is complied and starts running

Exceptions can prevent the code from stop executing (crashes).

File I/O

Scanner, FileReader, and BufferedReader classes are being used in order to read file in java.

the below example reads text.txt file and prints out its text to the screen

  public class ReadFiles {
      public static void main(String[] args){
          Scanner scanner = null;
          try{
              scanner = new Scanner(new BufferedReader(new FileReader("text.txt")));
              while(scanner.hasNext()){
                  System.out.println(scanner.nextLine());
              }
          }catch(IOException e){
              e.printStackTrace();
          }
      }
  }

Note: FileReader constructor argument must be the name of the file or the path for that file including its name and extension.