Java - Misc

Updated: 2021-02-21

Java Memory Model

Java Memory Model

The Java memory model describes how threads in the Java programming language interact through memory. The Java memory model defines when changes to memory made by one thread become visible to another thread

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