Contents

Java Notes

Basics

  1. SourceCode.java -> Compile (javac source_code.java) -> Java bytecode (SourceCode.class) ->Run by the Java Virtual Machine (java SouceCode)

    Write once, run anywhere!

  2. Every Java app must have at least one class and at least one main method (one main per app not per class.)

    1
    2
    3
    
    public static void main (String[] args) {
        // code
    }
    
  3. int rand = (int) (Math.random() * 10) to get random integers in range [0, 9]. (Math is a Java class.)

  4. To use float, we need to append f to the value. This is because Java treats everything with a floating point as double: float f = 3.14f

  5. Instance variables always get a default value, even if we don’t initialize it: int 0; float 0.0; boolean false; reference null.

  6. Use == for primitive types and references; .equals() for different objects (for example string objects). (== checks the reference/address and .equals checks the content.)

    1
    2
    3
    4
    5
    6
    7
    8
    
    public class Test {
        public static void main(String[] args) {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        System.out.println(s1 == s2); // false
        System.out.println(s1.equals(s2)); // true
        }
    }
    
  7. Integer.parseInt("42") converts a string to an int using the Java Integer class.

  8. The Stack and the Heap:

    • The Stack: all method invocations and local variables (aka, stack variables) live here.
      • The method on the top of the stack is always the currently executing method. When it’s removed from the stack, the method is executed, which the executing sequence for constructor chaining.
    • The Heap: all objects live here. Also know as the garbage-collectible heap.
      • Instance variables live inside the objects.
    • If the local variable is a reference to an object, the variable (the reference) goes on the stack, and the object is still on the heap.
  9. Use String.valueOf() to convert nearly anything (including a char array) to String.

  10. C printf() like formatting:

    1
    2
    
    String s = String.format(%d, 1);
    System.out.println(s);
    
  11. .length for primitive types (e.g. int[], String[]), .length() for objects (e.g. String). And .size() for collections.

  12. Integer.MAX_VALUE and Integer.MIN_VALUE.

Java Data Structures

  1. ArrayList: (inside the java.util (utility) class) (for primitive types, Java 5 and above enabled autoboxing: ArrayList<Integer>)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    
    import java.util.*
    class Foo {
        public static void main(String[] args) {
            List<String> A = new ArrayList<String>();
            A.add("hello");
            A.add("world");
            System.out.println("Size is: " + A.size());
            System.out.println("Contains hello? " + A.contains("hello"));
            System.out.println("Index of hello? " + A.indexOf("hello"));
            A.remove("hello"); // by value
            A.remove(0); // by index
            System.out.println("Empty? " + A.isEmpty());
        }
    }
    
  2. Arrays.asList(foo) and .toArray(new int[0])

  3. Comparator:

    1
    2
    3
    4
    5
    6
    
    Arrays.sort(intervals, new Comparator<int[]>() {
        @Override
        public int compare(int[] interval1, int[] interval2) {
            return interval1[0] - interval2[0]; // negative, smaller; 0, equal; positive, bigger
        }
    });
    
  4. When using an interface, we usually use implementations like: List<T> = new ArrayList<T>(), Queue<T> = new LinkedList<T>()

  5. Array:

    • int[] array = new int[]{1,2,3};

    • Array static methods: binarySearch(A, 42), copyOf(A), sort(A).

  6. String:

    • Methods: charAt(1), indexOf('A'), replace('a', 'A'), replace("a", "abc"), substring(1,4), toCharArray(), toLowerCase(), String[] words = s.split(" ")

    • if (string == null || string.isEmpty())

    • StringBuilder: String reversed = new StringBuilder(s).reverse().toString(), .trim() (removes leading and trailing spaces)

  7. Map:

    • Initialize a map:

      1
      2
      3
      4
      5
      6
      7
      
      Map<Character, Integer> map = new HashMap<Character, Integer>() {
          {
              put('I', 1);
              put('V', 5);
              put('X', 10);
          }
      };
      
    • for (int i : map.keySet()); or

      1
      2
      3
      4
      5
      
      for (Map.Entry<String, Object> entry : map.entrySet()) {
          String key = entry.getKey();
          Object value = entry.getValue();
          // ...
      }
      
    • map.put(i, map.get(i)+1);

    • map.containsKey();

    • A TreeMap is a binary search tree (SortedMap) implementation. It’s naturally sorted by keys. SortedMap<Integer, String> sm = new TreeMap<Integer, String>();

References and Garbage Collection

  1. Garbage collection:

    1
    2
    3
    4
    5
    6
    7
    
    Book b = new Book();
    Book c = new Book();
    // By far, 2 references and 2 objects.
    Book d = c; // d and c refer to the same object
    // 3 references and 2 objects.
    c = b; // c refers to b's object now
    // 3 references and 2 objects.
    
    1
    2
    3
    4
    5
    6
    7
    
    Book b = new Book();
    Book c = new Book();
    b = c; // b and c refer to the same object
    // 2 references, 1 reachable object, 1 abandoned object.
    // b's original object eligible for garbage collection
    c = null; //null reference
    // 1 active reference, 1 reachable object
    
  2. Array of objects:

    1
    2
    3
    4
    5
    6
    7
    
    Book[] books;
    books = new Book[10];
    // By far, only an array of references, no objects created.
    // To create the objects:
    for (int i = 0; i < 10; i++) {
        Book[i] = new Book();
    }
    

Static

  1. All static variables are initialized before any object can be created.

    1
    2
    3
    4
    5
    6
    
    public class foo {
        static int count = 0;
        public increment() {
            count++;
        }
    }
    
  2. Static final variables are constants: public static final double PI = 3.141592653589793; (In uppercase by convention.) Or we can use the static initializer which runs before any code in the class:

    1
    2
    3
    4
    5
    
    public class foo {
        static {
            // code``
        }
    }
    

Exceptions

  1. The method that throws must declare throws Exception:

    1
    2
    3
    4
    5
    
    public class Solution {
        public static void main(String args[] ) throws Exception {
            throw new IllegalArgumentException("Invalid Input");
        }
    }
    
  2. The finally block always runs no matter what:

    1
    2
    3
    4
    5
    6
    7
    
    try {
        // code
    } catch (//some exception) {
        // code
    } finally {
        // code
    }
    

I/O

  1. Example:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    import java.util.Scanner;
    
    class MyClass {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            System.out.println("Enter name, age and salary:");
    
            // String input
            String name = scanner.nextLine();
    
            // Numerical input
            int age = scanner.nextInt();
            double salary = scanner.nextDouble();
    
            // Output input by user
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Salary: " + salary);
        }
    }
    

Constructors

  1. Invoking an overloaded constructor: call this();. However, we can only call this() OR super(), never both inside a constructor.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    
    public class Bar extends Foo {
        String name;
        public Bar() {
            this("Hello"); // MUST BE THE FIRST STATEMENT!!!
            // code
        }
        public Bar(name) {
            // code
        }
    }
    

Polymorphism

  1. With polymorphism, the reference type can be a superclass of the object type.

    1
    2
    3
    4
    5
    6
    
    Animal[] animals = new Animal[2];
    animals[0] = new Dog();
    animals[1] = new Cat();
    for (Animal animal : animals) {
        animal.make_sound(); // mew and bark
    }
    
  2. We can also have polymorphic arguments and return types. (When a superclass type is requested, a subclass is sufficient to use.)

  3. Rules for overriding:

    • Arguments must be the same, and return types must be compatible.
    • The method can’t be less accessible.
  4. Abstract:

    • Use abstract to make the base class abstract. public abstract class animal {} (can’t be instantiated.)
    • Use abstract to make a method abstract public abstract void eat(); (also no method body!)
    • Abstract methods must be put in abstract classes.
    • We must implement abstract methods by overriding.
  5. Every class in Java extends the Object class which has the methods like: .equals(), .hashCode(), .getClass().

References