logo

Java - Misc

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:

primitive(stack)

char c = 'x';

wrapper(heap)

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

http://docs.oracle.com/javase/tutorial/deployment/jar/downman.html

Why no Operator overloading

Operator overloading always leads to abuse

Null

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

https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained

Runnable vs Callable

Runnable does not return any value, while Callable does.

Call one constructor from another(multiple constructors exist)

  • use this

Criticism

"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.

Immutability

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

How to calculate memory usage

32-bit JVMs have a limit smaller than 4GiB due to other JVM and OS overhead, and differs depending on the OS.

Each Java object has a header:

  • one machine word for a reference to the object's class
  • one machine word for some flags used by the garbage collector and to manage synchronization (using partial words would be bad for performance)

So that's 2 words, which is 8 bytes on 32 bit systems, and 16 bytes on 64 bit.

Arrays additionally need an int field for the array length, which is another 4 bytes, possibly 8 on 64 bit systems.

Compressed oops

In 64-bit mode, references are double the size, increasing memory consumption.

If Compressed oops is enabled, object references are shrunk to 4 bytes, with the caveat that the heap is limited to four billion objects (and 32GB Xmx).

Compressed oops are not free: there is a small computational cost to achieve this big reduction in memory consumption.