Started working on Android Development and brushing up my Java as I worked on more projects.

JMH : Java Microbenchmarking Harness

I attended PJUG last night and they had a talk about microbenchmarking in Java. The talk started with what might be the most important things to keep in mind for any benchmarking code.

  • avoid dead code elimination by always return output or use blackhole
    • An example is that if the code you are benchmarking doesn’t do anything, the optimizer might interpret it as dead code and never translate that into bytecode at all. However, if the result in the dead code is being return, then optimizer won’t be able to eliminate the code away.
  • avoid constant folding by reading input from state objects
    • If at some point inside the code for benchmarking where a function is taking a constant as argument and return the same value every time , then the optimizer again will interpret the return value as a constant as well even though you might be benchmarking the execution of the function. In this case, move the constant out and make it into a field in your class so that the function argument becomes a variable.

Other interesting topic were monomorphic, bimorphic and megamorphic, and concurrency issue with jmh. The full presentation slides is here.

Additional References:


Java Koans – Intermediate

These are some notes from the Java Koans that is part of the assignment from the Advance Java Programming Class from PSU CS410J.


  • Some reference regarding boxing in Java
  • auto-boxing example: int-> Integer, long-> Long
  • auto-unboxing example: Float->float, Boolean->boolean
  • auto-unboxing a null Object will cause a NullPointerException
int x = 1;
Integer y = new Integer(x);
x == y;      // auto-unbox y and compare value
x.equals(y); // will not compile regardless what y is
y.equals(x); // auto-box x and compare value


  • List, ArrayList method add and get
  • Queue, PriorityQueue method add, peek, size, poll, isEmpty
  • Set, HashSet method add, size, contains
  • Map, HashMap method put, size, containsKey, containsValue, get.
  • Both the list and array reference to the same array “list” and if one of the element changes, the same element in the other one changes as well because of the same reference.
String[] array = {"a","b","c"};
List<String> list = Arrays.asList(array);
  • TreeMap and SortedMap. backedMap is a subMap of map which mean backedMap is a view of map. backedMap references to map and if we add something to backedMap, we are essentially adding it into map.
TreeMap<String, String> map = new TreeMap<String, String>();
map.put("a", "Aha");
map.put("b", "Boo");
map.put("c", "Coon");
map.put("e", "Emu");
map.put("f", "Fox");
SortedMap<String, String> backedMap = map.subMap("c", "f");
  • TreeSet is an ordered set and LinkedHashSet is a linked list implementation of set with predictable iteration order.


  • a.compareTo(b) return 0 if equal, 1 if a > b and -1 if a < b.
  • implements Comparable to make Objects comparable.
  • implements Comparator to impose ordering.


  • Jan 1, 1970 GMT is the origin date and time. 1L = 1 millisecond pass the origin data and time.
  • Date references.
  • add() add the value to the whole date value. e.g. July 1, 1970 and add 8 months will give March 1, 1971.
  • roll() does not change the larger value. e.g. July 1, 1970 and roll 8 months will give March 1, 1970 where year is unchanged.
  • Date format using getDateInstance().format
    • no arg or Date.format.MEDIUM: MON D, YYYY
    • Date.format.SHORT: M/D/YY
    • Date.format.FULL: DayOfWeek, Month D, YYYY
    • custom date using M=month, D=day and Y=year.


  • Object == Object compare identity
  • Object.equals(Object) compare value
  • null vs Object discussion here.
  • override equals() and hashcode(). Here is another references.


  • File createNewFile() and delete() does what it said.
  • FileWriter write() and close() are self explanatory. flush() is a Flushable that write any buffered output to the underlying stream.
  • FileReader read() and close().
  • Here we write to a file using a string (size = 22), then we created a larger char array (new char[50]) and read the file into the char array. At the end, we turn the char array back to a string. The size of the read is 22, but the size of the char array and the size of the string that created from the char array after the read is still 50 even though it only output 22 characters when println.
File file = new File("file.txt");
FileWriter fw = new FileWriter(file);
fw.write("First line\nSecond line");

char[] in = new char[50]; // <-- start with 50 empty char
int size = 0;
FileReader fr = new FileReader(file);
size =; // <-- fill up 22 char with 28 empty char left

// size of read == length of the original string
assertEquals(size, "First line\nSecond line".length());
// the size of the char array string is still 50!
assertEquals((new String(in)).length(), 50);
assertEquals("First line\nSecond line".length(), 22);
// finally the char array string has 28 empty character at the end!
assertEquals(new String(in), "First line\nSecond line"+(new String(new char[28])));


  • If OtherInner extends AboutInnerClasses, then an OtherInner object is instanceof AboutInnerClasses as well.


  • Locale with getDisplayCountry, Use with getDateInstance and getCurrencyInstance … etc.
  • Language and Country code


  • Pattern compile is the pattern to match
  • Matcher has the string to check for a pattern to match with.
    • find() return boolean of whether it find the pattern
    • start() return index of the last matched
    • “\\.” mean match a “.” period.
    • .split(delimiter) split up a string into an array of string base on the delimiter


  • Additional References regarding Serialization. 1 2 3
  • If the subclass that implements serializable has a superclass that does not implement serializable and the constructor of the superclass is invoke from the subclass, serialization will not happen.

Java Koans – Beginner – Part 2

These are some notes from the Java Koans that is part of the assignment from the Advance Java Programming Class from PSU CS410J.


  • overridden methods may returns subtype
class Parent {
  public String doStuff() { return "parent"; }
class Child extends Parent {
  // override Parent.doStuff()
  public String doStuff() { return "child"; }   
  // overload Child.doStuff()
  public String doStuff(String s) { return s; } 

abstract class ParentTwo {
  abstract public Collection<?> doStuff();

class ChildTwo extends ParentTwo {  
  // must implement doStuff()
  public Collection<?> doStuff() { return Collections.emptyList(); };


  • Downcast and Upcasting explain in here.
  • In term of the code in koans, Child extends from Parent extends from Grandparent mean child is a Child, Parent and Grandparent. However, parentReference is still a Child when upcast from Child to Parent because Child property is only hidden until being it is being downcast back to Child again.
Child child = new Child();
// upcasting always allow
Parent parentReference = child;
assertEquals(child instanceof Child, true);
assertEquals(parentReference instanceof Child, true);
assertEquals(parentReference instanceof Parent, true);
assertEquals(parentReference instanceof Grandparent, true);
  • Here, since child was originally a Child, we can downcast it back to Child with explicit downcast.
// implicit upcast
Grandparent child = new Child(); 
// explicit downcasts
Parent parentReference = (Parent) child;  
Child childReference = (Child) parentReference; 
assertEquals(childReference instanceof Child, true);
assertEquals(childReference instanceof Parent, true);
assertEquals(childReference instanceof Grandparent, true);

Child child2 = new Child()
// implicit upcast
Parent parentReference2 = chlid2;
// access Child.complain() instead of Parent.complain()
assertEquals(parentReference2.complain(), "Are we..");

// implicit upcast
Grandparent parent = new Parent();
// access Parent.complain() by explicit downcast the object back to Parent before invoking complain()
assertEquals("TPS...", ((Parent) parent).complain());


  • For nested if-else statement, else is bound to the closest if when there is no curly bracket.


  • All inherited constructors are first called before its own constructor. Example from another source as well.
class A {
  String someString = "a";
   public A() { someString += "x"; }
class B extends A {
  public B() { someString += "g"; };
public void simpleConstructorOrder(){
  assertEquals(new B().someString, "axg");


  • The private member of enum acts like the private member of inner class when access by the containing class. A better example.


  • finally is always ran! So return statement in finally will always be the return value.


  • The signature of the arguments will upcast to Object when they don’t fit. If comment out first line in class A, the first assert statement will equals to “Integer”. If comment out second line and uncomment the first line in class A, the second assert statement will equals to “int”.
class A {
  public String doStuff(int i) { return "int"; }
  public String doStuff(Integer i) { return "Integer"; }
  public String doStuff(Object i) { return "Object"; }
  public String doStuff(int...i) { return "int vararg"; }
  public String doStuff(Object...i) { return "obj vararg"; }

// assert statements
assertEquals(new A().doStuff(1), "int");
assertEquals(new A().doStuff(Integer.valueOf(1)), "Integer");
assertEquals(new A().doStuff(1l), "Object");
assertEquals(new A().doStuff(1, Double.valueOf(2)), "obj vararg");


  • full AND: &
  • short circuit AND: &&
  • write (true == a) to ensure it is a predicate and not an assignment (a = true).


  • use Arrays.equals() to compare element by element equality between two arrays.

Java Koans – Beginner – Part 1

These are some notes from the Java Koans that is part of the assignment from the Advance Java Programming Class from PSU CS410J.


  • == test if two objects are the same objects
  • equals method also test if two objects are the same
  • however, the subclass can change equals method to test if two objects are equal
Object object = new Integer(1);
Object diffObject = new Integer(1);
assertEquals(object.equals(object), true);
assertEquals(object.equals(diffObject), true);
assertEquals(object == diffObject, false);
  • new object does not equal to null


  • primitive type : its object type : size : MIN_VALUE : MAX_VALUE
    • int:Integer:32:-2147483648:2147483647
    • long:Long:64:-9223372036854775808l: 9223372036854775807l
    • short:Short:16:-32768:32767
    • byte:Byte:8:-128:127
    • char:Character:16:0:65535
    • double:Double:64:4.9E-324:1.7976931348623157E308
    • float:Float:32:1.4E-45f:3.4028235E38f
assertEquals(getType(1), int.class);
Object number = 1;
assertEquals(getType(number), Integer.class);
assertEquals(Integer.Size, 32);


  • new String() equals to “” (empty string)
  • MessageFormat allow reuse of same arguments in the token
assertEquals(MessageFormat.format("{0} {1} {0}", "a", "b"), "a b a");
assertEquals(MessageFormat.format("{0} {1} {0}", "a", "b", "c"), "a b a");
assertEquals(MessageFormat.format("{0} {1} {0}", "a"), "a {1} a");


  • toString() is the same as Object.class.getName() @ Integer.toHexString(object.hashCode())) if it is not override.


  • for loop
    • for (int j : lst) –> where lst is an array of int.
  • for loop continue with label mean execution stop in the inner loop but continue for the outerloop in this case. (count += 10 never executed). In contrast, the count = 75 without the label.
    • enter the outer for loop with i = 0
      • enter the inner for loop with j = 0
        • increment count to 1
        • repeat inner loop for j = 1, 2 and count = 1 + 2 =3
        • count > 2 so continue to outerLabel
    • repeat outer loop for i = 1, enter inner loop for j=0 with count = 4 and hit continue outerLabel again
    • do this until i = 5 (i = 2, 3, 4 and count = 4+3 = 7).
public void forLoopContinueLabel() {
  int count = 0;
  for(int i = 0; i < 5; i++) {
    for(int j = 0; j < 5; j++) {
      if(count > 2) {
        continue outerLabel; 
    count += 10;
  // What does continue with a label mean? 
  // What gets executed? Where does the program flow continue?
  assertEquals(count, 7);
  • for loop break with label mean execution leave all loop in this case and continue after the outer for loop. In contrast, count = 57 without the label.
    • enter the outer loop with i = 0
      • enter the inner loop with j = 0
        • increment count to 1
        • repeat inner loop for j = 1, 2 and count = 1 + 2 = 3
        • count > 2 so break to outerLabel and done.
    public void forLoopBreakLabel() {
        int count = 0;
        for(int i = 0; i < 5; i++) {
            for(int j = 0; j < 5; j++)
                if(count > 2) {
                    break outerLabel;    
            count += 10;
        // What does break with a label mean? 
        // What gets executed? Where does the program flow continue?
        assertEquals(count, 3);

Chapter 5: Object-Oriented Programming

5.1 Software Reuse and Independence

  • Four basic way that a software component can be modified for reuse
    • extension of the data or operations
    • redefinition of one or more of the operations
    • abstraction
    • polymorphism

5.2 Smalltalk

5.3 Java

  • Some of the Java feature include garbage collection and use of references instead of explicit pointers.
  • Basic Elements of Java: Classes, Objects and Methods.
    • Constructor chaining is when one constructor call another constructor with argument.
  • The Java Collection Framework: Interfaces, Inheritance, and Polymorphism
    • An interfaces is a set of operations on objects of a given type. Interfaces serve as the glue that connects components in software systems.
    • If a class implements an interface, any of its subclasses also (implicitly) implement that interface.
    • Abstract class implement common properties and behavior for their subclasses. Concrete classes can be instantiated.
    • listOfStrings and listOfChars above are just List. Same methods can be called on the two List variable even though the two lists they reference have different implementations and different element types. The variable queueOfFloats has been declared Queue<Float> and so the LinkedList that it refers to are using the methods specified in the Queue interface.
List<String> listOfStrings = new LinkedList<String>();
Queue<Float> queueOfFloats = new LinkedList<Float>();
List<Character> listOfChars = new ArrayList<Character>();
  • Dynamic Binding and Static Binding
    • Dynamic binding is when method being called upon an object is looked up by name at runtime.
    • Java complier statically determines which implementation of a method to use when the receiver object’s actual class can be determined at compile time. However, it will not actually generate code for static binding unless the method has been defined as final or static.
      • final method cannot be overridden in a subclass
      • static method call on a class rather than an instance.

5.4 C++

  • Basic Element of C++: Classes, Data Members, and Member Functions
    • Instance variables and methods are both members of the class (data member and member function, respectively).
    • public, protected, or private member are accessible by client code and derived class, only derived class, or none, respectively.
  • Static Binding, Dynamic Binding and Virtual Functions
    • All member functions are statically bound at compile time. Only function defined using the keyword virtual are candidates for dynamic binding.
    • pure virtual declaration in an abstract class by use the keyword virtual along with the function = 0.
    • Example of repeated inheritance (two separate copies of object of class A) vs shared inheritance (using virtual keyword).
class A {...};
class B : public A {...};
class C : public A {...};
class D : public B, public C {...};

A     A
|     |
B     C
 \   /
class A {...};
class B : virtual public A {...};
class C : virtual public A {...};
class D : public B, public C {...};

 /   \
B     C
 \   /

5.5 Design Issues in Object-Oriented Languages

  • Classes vs Types
    • Possible incorporation of classes into the type system.
      • As typeless entities and exclude from type checking (Objective-C).
      • As type constructors and must be incorporated into type checking (C++). Compatibility of objects of descendent classes to objects of ancestor classes complicates type checking (e.g. x is descendent of y, so y = x but flag x = y.)
      • As a type system itself (Smalltalk, Java).
  • Classes vs Modules
    • Code that uses a class becomes dependent on the particular implementation of the class even if it cannot make use of the details of that implementation.
  • Inheritance vs Polymorphism
    • Four basic kinds of polymorphism
      • parametric polymorphism in which type parameters may remain unspecified in declaration (e.g. C++ template).
      • Overloading in which different function or method declarations share the same name and are disambiguated through the use of the types of the parameters in each declaration.
      • Subtype polymorphism in which all the operations of one type can be applied to another type.
      • Inheritance in which is a kind of subtype polymorphism and overloading.

5.6 Implementation Issues in Object-Oriented Languages

  • Implementation of Objects and Methods
    • The allocation of instance variable of super class precede those variable from derived class in the object instance so that the allocation of the variable within the object instance stay the same.
  • Inheritance and Dynamic Binding
    • Allocation of methods as pointer in the allocation of the object instance.

Additional Notes


Other Resources