Java - Misc

Updated: 2021-11-19

Autoboxing and Unboxing

Autoboxing: automatically convert from a primitive to a wrapper

The "wrapper" classes for the primitive data types allow you to make a non-primitive object on the heap to represent that primitive type. For example:


char c = 'x';


Character ch = new Character('x');
Character ch = 'x';

java -jar vs java -cp

Cannot use both!

  • java -jar: specify an executable jar, the classpath should be specified in Manifest
  • java -cp: specify classpath

Why no Operator overloading

Operator overloading always leads to abuse


do not use null values in a set or as a key in a map.

Set.isEmpty() does not check for null

if null is needed, use Collections.unmodifiableList() otherwise use Guava's ImmutableList

Runnable vs Callable

Runnable does not return any value, while Callable does.

Call one constructor from another(multiple constructors exist)

  • use this


"A major oversight in the design of Java is the lack of conditional compilation" (#ifdef/#endif). Instead the traditional OO solution is to create a super class and then add extra methods.


The class must be final (or ban subclassing by having only private constructors, or be known to have only subclasses which also satisfy these constraints) and all its fields must be final and either primitive or objects which are themselves immutable (in this strict sense).

Loop Performance

List<Integer> list;

// A
for (Integer k : list) {

// B
for (int i = 0; i < list.size(); i++) {
    Integer k = list.get(i);

// C
int len = list.size();
for (int i = 0; i < len; i++) {
    Integer k = list.get(i);

B: list.size() will be calculated in each iteration

A vs C: if list is ArrayList, they are the same, each iteration O(1); if LinkedList list.get(i) will take O(N);

Java UI Libs

  • Swing
  • JavaFX