Java Notes
- Basics
- Java Data Structures
- References and Garbage Collection
- Static
- Exceptions
- I/O
- Constructors
- Polymorphism
- References
Basics
-
SourceCode.java -> Compile (
javac source_code.java
) -> Java bytecode (SourceCode.class) ->Run by the Java Virtual Machine (java SouceCode
)Write once, run anywhere!
-
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 }
-
int rand = (int) (Math.random() * 10)
to get random integers in range [0, 9]. (Math is a Java class.) -
To use
float
, we need to appendf
to the value. This is because Java treats everything with a floating point asdouble
:float f = 3.14f
-
Instance variables always get a default value, even if we don’t initialize it:
int 0
;float 0.0
;boolean false
;reference null
. -
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 } }
-
Integer.parseInt("42")
converts a string to an int using the Java Integer class. -
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.
- The Stack: all method invocations and local variables (aka, stack variables) live here.
-
Use
String.valueOf()
to convert nearly anything (including a char array) to String. -
C
printf()
like formatting:1 2
String s = String.format(%d, 1); System.out.println(s);
-
.length
for primitive types (e.g. int[], String[]),.length()
for objects (e.g. String). And.size()
for collections. -
Integer.MAX_VALUE
andInteger.MIN_VALUE
. -
Character.toLowerCase()
andCharacter.isLetterOrDigit()
. -
Convert a char array to string
String.valueOf(charArray)
;
Java Data Structures
-
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 15 16 17 18 19
import java.util.* class Foo { public static void main(String[] args) { List<String> A = new ArrayList<>(); 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()); List<String> myStringList = Arrays.asList("apple", "banana", "cherry"); String result = String.join(", ", myStringList); // double quotes A.get(0); A.set(0, "new one"); A.addAll(B); // concatenate all from B } }
-
Arrays.asList(foo)
converts arrays to lists and.toArray(new Integer[0])
converts lists to arrays (new int[0]) is the type hint. Can’t convert to a primitive array directly. -
Comparator
:1 2 3 4 5 6 7 8
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 } }); // Java 8: Arrays.sort(intervals, (interval1, interval2) -> (interval1[0] - interval2[0]));
-
When using an interface, we usually use implementations like:
List<T> = new ArrayList<T>()
,Queue<T> = new LinkedList<T>()
-
Array:
-
int[] array = new int[] {1,2,3};
(Can NOT specify the dimension here.) -
Arrays static methods:
binarySearch(A, 42)
,copyOf(A)
,sort(A)
. -
Arrays.sort(intervals, (x, y) -> Integer.compare(x[0], y[0]));
-
2D array
int[][] grid = new int[10][10]
; -
Array of lists:
1 2 3 4
List<Integer>[] foo = new List[10]; for (int i = 0; i < 10; i++) { foo[i] = new ArrayList<>(); };
-
Arrays.fill(arr, 1)
fills the array with 1s.
-
-
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).append()
anddeleteCharAt()
.
-
-
Map:
-
Initialize a map:
1 2 3 4 5
Map<Character, Integer> map = new HashMap<>() {{ put('I', 1); put('V', 5); put('X', 10); }};
-
for (int i : map.keySet());
or1 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();
-
map.values()
; -
A
TreeMap
is a binary search tree (SortedMap
) implementation. It’s naturally sorted by keys.SortedMap<Integer, String> sm = new TreeMap<Integer, String>();
-
-
Stack:
- Initialization:
Stack<Integer> stack = new Stack<>();
- Common Methods:
- push(element): Adds an element to the top.
- pop(): Removes and returns the top element.
- peek(): Returns the top element without removal.
- isEmpty(): Checks if the stack is empty.
- Initialization:
-
Queue (Interface in Java, often realized using LinkedList):
- Initialization:
Queue<Integer> queue = new LinkedList<>();
- Common Methods:
- offer(element): Adds an element to the end (returns true if success, false if not). Or we can use add(), but it throws an exception when it fails to add.
- poll(): Removes and returns the front element.
- peek(): Returns the front element without removal.
- Initialization:
-
PriorityQueue (Binary min heap):
- Initialization:
PriorityQueue<Integer> pq = new PriorityQueue<>();
- Common Methods:
- offer(element): Adds an element. (Can also use add()).
- poll(): Removes and returns the smallest element.
- peek(): Returns the smallest element without removal
- Max heap:
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());
- Initialization:
-
Ternary operator:
x = y == z ? y : z
; -
ceiling is
Math.ceil((double) x / y)
;
References and Garbage Collection
-
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
-
Array of objects or collections:
1 2 3 4 5 6 7 8 9 10 11
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++) { books[i] = new Book(); } Set<Integer>[] sets = new HashSet[10]; for (int i = 0; i < 10; i++>) { sets[i] = new HashSet<>(); }
Static
-
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++; } }
-
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
-
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"); } }
-
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
-
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
-
Invoking an overloaded constructor: call
this();
. However, we can only callthis()
ORsuper()
, 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
-
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 }
-
We can also have polymorphic arguments and return types. (When a superclass type is requested, a subclass is sufficient to use.)
-
Rules for overriding:
- Arguments must be the same, and return types must be compatible.
- The method can’t be less accessible.
-
Abstract:
- Use
abstract
to make the base class abstract.public abstract class animal {}
(can’t be instantiated.) - Use
abstract
to make a method abstractpublic abstract void eat();
(also no method body!) - Abstract methods must be put in abstract classes.
- We must implement abstract methods by overriding.
- Use
-
Every class in Java extends the Object class which has the methods like:
.equals()
,.hashCode()
,.getClass()
.