View on GitHub

reading-notes

Maps, primitives, File I/O

Java Primitives versus Objects

1. Java Type System

Java has a two-fold type system consisting of primitives such as int, boolean and reference types such as Integer, Boolean. Every primitive type corresponds to a reference type.

Objects => reference type in Java are slower and have a bigger memory impact than their primitive analogs.

Exceptions

The Java programming language uses exceptions to handle errors and other exceptional event

How to Throw Exceptions

Throwing an exception is as simple as using the “throw” statement.

Example:

public static void main(String[] args) {
	Scanner kb = new Scanner(System.in);
    System.out.println("Enter a number");
    try {
    	double nb1 = kb.nextDouble();
    	if(nb1<0)
        	throw new ArithmeticException();
        else System.out.println( "result : " + Math.sqrt(nb1) );
    } catch (ArithmeticException e) {
        System.out.println("You tried an impossible sqrt");
    }
}
}

The Three Kinds of Exceptions

  1. checked exception.
  2. error.
  3. runtime exception.
A program can catch exceptions by using a combination of the try, catch, and finally blocks.

The try statement should contain at least one catch block or a finally block and may have multiple catch blocks.

Scanning

Objects of type Scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type.

Example:

import java.io.*;
import java.util.Scanner;

public class ScanXan {
    public static void main(String[] args) throws IOException {

        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));

            while (s.hasNext()) {
                System.out.println(s.next());
            }
        } finally {
            if (s != null) {
                s.close();
            }
        }
    }
}