- Keep result of mod be positive.
Math.floorMod(-1, 10); // 9
- Quick-and-dirty list of the elements of a two-dimensional array
System.out.println(Arrays.deepToString(arrays));
- In java, arrays of subclass references can be converted to arrays of supperclass reference without a cast. But attempting to store an Employee reference causes an ArrayStoreException at runtime.
// Manager is superclass of Employee
Manager[] managers = new Manager[2];
managers[0] = new Manager();
Employee[] employees = managers;
// compile succeed, runtime exception java.lang.ArrayStoreException
employees[0] = new Employee();
- If the subclass constructor does not call a superclass constructor explicitly, the no-argument constructor of the superclass is invoked. If the superclass does not have a no-argument constructor and the subclass constructor does not call another superclass constructor explicitly, the Java compiler reports an error.
class Employee {
public Employee(int id) {
}
}
class Manager extends Employee {
// Compile Error: Implicit super constructor Employee() is undefined
public Manager(int id, String name) {
}
}
- Nowadays, some Unicode characters can be described with one char value, and other Unicode characters require two char values.
"𝕆".length(); // 2
"A".length(); // 1
- If the method is private, static, final, or a constructor, then the compiler knows exactly which method to call. This is called static binding. Otherwise the method to be called depends on the actual type of the implicit parameter and dynamic binding must be used at runtime.
class Employee {
public static void getInstance() {
System.out.println("Employee");
}
}
class Manager extends Employee {
public static void getInstance() {
System.out.println("Manager");
}
}
public class Inheri {
public static void main(String[] args) {
Employee e = new Manager();
e.getInstance(); // Employee
Manager m = new Manager();
m.getInstance(); // Manager
}
}