Java Basics Summary

Here I will write down some key concepts about Java when I read Head First Java.
Notes written by others: link

9.16

1 Dive in a Quick Dip

How java works:
Source --> Compiler --> Output --> Virtual Machine

A Java program/application only has one main method

2 Classes and Objects

Inheritance: “Square inherits from Shape.” The Shape class is called the superclass of the other four classes. The other four classes are the subclasses of Shape, inheriting the methods of the superclass.

Overriding: a subclass refines one of its inherited methods when it needs to change/extend the behavior of that method.

Instance variables: things an object knows about itself; represent state(data), can have unique values for each object of that type.

Method: things an object can do.

Class: a blueprint for an object. Tell VM how to make an object of that particular type.

Dot operator (.): access to state/instance var and behavior/methods.

main: test real class; launch/start Java app

(Garbage Collection) Heap: where the created object is stored. Java allocates memory space on the heap according to how much that particular created object needs.

3 Primitives and References

primitives: hold fundamental values – int (32 bits), boolean, float (32 bits), char(16 bits), double (64 bits), byte (8 bits), short (16 bits), long (64 bits)

object references: hold references to objects

Variables must have a type and name.

1
float f = 32.5f; // Java think anything with a floating point is a double, so add 'f'

Name: start with a letter/_/$ not number; no use of reserved words

1
Dog myDog = new Dog(); // declare a reference variable, create an object, link them

Arrays are always objects, whether they are declared to hold primitives/object references.

4 Methods Use Instance Variables

A method uses parameters. A caller passes arguments.

Java is pass-by-value, which means it pass-by-copy.

  1. int is one of the 8 basic variables, and int[] is reference variable.
  2. In a Java method, method arguments(MA) are passed by by value.
  3. if basic variables are in MA, the value is copied, and the initial variable remain unchanged.
  4. if reference variable is in MA, the address is copied (and passed as value), and the initial variable will be changed.

7 Inheritance and Polymorphism

Polymorphism example: Animal myDog = new Dog();
The reference variable type is declared as Animal, but the object is. created as new Dog().
With polymorphism, the reference type can be a superclass of the actual object type.

1
2
3
4

Animal[] animals = new Animal[5];
animals[0] = new Dog();
animals[1] = new Cat();

Make a class private: if you need security
Make a method/class final: protect a specific method from being overridden; want to guarantee that none of the methods in that class will ever be overridden.

Overriding rules:

  1. arguments must be the same, and return types must be compatible
  2. the method can’t be less accessible

Overloading rules:

  1. return types can be different
  2. cannot change only the return type (also change the argument list)
  3. can vary the access levels in any direction

8 Interfaces and Abstract Classes

Abstract class:

  1. has no body
  2. if declare an abstract method, must also mark the class abstract
  3. good for: polymorphism, inheritable method implementations
  4. concrete class must implement all abstract methods (like overriding)

Every class in Java extends class Object.
Interface: all methods are abstract

1
2
public interface Pet{...}
public class Dog extends Canine implements Pet{...}

Encapsulation

Mark instance variables private, mark getters and setter public.

The signed left shift operator “<<” shifts a bit pattern to the left
The signed right shift operator “>>” shifts a bit pattern to the right.
The unsigned right shift operator “>>>” shifts a zero into the leftmost position

String

Commonly used methods: charAt, indexOf, length, split, toCharArray, trim, replaceAll, compareTo, equals, startsWith, endsWith, toLowerCase, toUpperCase, valueOf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
String[] pets = {"a", "b", "c"};

// they are the same
String str = "abc";
char data[] = {'a', 'b', 'c'};
String str = new String(data);

// more examples
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);

"cares".concat("s"); // returns "caress"
"to".concat("get").concat("her") // returns "together"

Maps

Common methods: Map.Entry<K,V>, containsKey, getOrDefault, isEmpty, keySet, putIfAbsent, remove, replace, size, entrySet

HashMap, TreeMap, LinkedHashMap, Hashtable

HashMap is implemented as a hash table, and there is no ordering on keys or values. HashMap doesn’t allow two identical elements (same key+value, but same key different values is fine!).
TreeMap is implemented based on red-black tree structure, and it is ordered by the key. A TreeMap is sorted by keys.
LinkedHashMap preserves the insertion order. LinkedHashMap is a subclass of HashMap. That means it inherits the features of HashMap. In addition, the linked list preserves the insertion-order.
Hashtable is synchronized, in contrast to HashMap.
From Java Doc: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.

Set

Common methods: add, contains, isEmpty, remove, toArray, size

TreeSet

Common methods: first, last

Priority Queue with custom comparator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// not necessary to specify the capacity
PriorityQueue<Node> pq = new PriorityQueue<Node>(initCapacity, new Comparator<Node>() {
public int compare(Node n1, Node n2) { // type should be consistent
// compare n1 and n2
return str1.compareTo(str2);
// return s1-s2;
// return s1[0]-s2[0];
}
});

// Using lambda expression
PriorityQueue<String> pq = new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());

// max heap
PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());

Scanner

1
2
3
4
5
6
7
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
String s = sc.nextLine();
// int i = sc.nextInt();
// do more things
}
sc.close();

StringBuilder

Commonly used methods: append, charAt, delete, deleteCharAt, length, reverse, toString, setLength, substring, setCharAt, insert

1
2
3
StringBuilder str = new StringBuilder("AAAABBBCCCC"); 
System.out.println("String = "+ str.toString()); // print string
StringBuilder reverseStr = str.reverse(); // reverse the string

Arrays

Commonly used methods: asList, binarySearch, sort, equals, fill, toString