javap for debugging and better understanding some Java concepts with 3 practical examples

The javap is a class file dissembler. Here are 3 scenarios you can put javap to use with code examples.

#1 Finding the Java version of the class file within a jar

Extract a class file say “MyJobRunner.class” from a jar file and use javap to find out the version used

“major version: 51” means Java 7.

So, very useful for debugging Java version issues throwing errors like

#2 Finding or proving any inefficiencies in your code

Is there anything wrong with this code?

javap to dissemble

Output:

Hmm, what does this mean?

The dissembled code looks cryptic, but if you inspect it carefully the code within the public static java.lang.String withoutStringBuilder(int);

Line 5 to 32: is the code within the for loop. The “goto 5” indicates looping back.

Line 10: creates a new StringBuilder object every time

Line 18: uses the StringBuilder’s append method to concatenate the String.

Line 25: uses the toString( ) method to convert the StringBuilder back to the existing String reference via toString( ) method.

Inefficient code why?

if the count = 100, then 100 StringBuilder objects are created due to line 10, and 100 String objects out of which 99 will discarded due to line 25.

The efficient code would be

javap to dissemble

Output:

Why is it efficient?

As you could see

Line 0 to 6: initializes one StringBuilder object outside the for loop.

Line 12 to 26: is the for loop.

Line 19: indicates that since the StringBuilder is mutable, the string is appended via the append method.

So, it does not create unnecessary number of StringBuilder and String objects.

#3 Improves your understanding of Generics type erasure

Here is the sample code with Generics

In order to see the resulting code of “MyGeneric” does


Categories Menu - Q&As, FAQs & Tutorials

Top