The -g Debug Compiler Flag

Cartoon of bug being hit with a fly swatter

Occasionally you might have to debug your Java code. Now maybe your code is always correct, and never needs debugging, but then you might want to help someone else in the team who has a problem.

When we debug code, we want to have as much information about our code as possible. One of the problems we face when debugging is that the compiler strips the method parameter names and local variable names from the class file. If we’re stepping through our code, we would like to see the correct names in our debugger.

Inserting Debug Information

We can get the compiler to insert debugging information, including these omitted variable names, into the class files. We do this by using the -g flag when compiling.

javac -g

The resulting class file is bigger, but has a lot more debug info in it. You can view this information by running the class file disassembler javap from a command console. Do this before compiling with the -g flag and again afterwards to see the difference. Use the -v or -verbose flag:

javap -v MyClass

Using an IDE

You might not need to know about the -g debug flag if you’re using a modern IDE. If you’re debugging from within an IDE, you’ll probably be debugging by stepping through the source code. Be aware that behind the scenes, the IDE will be using the complete debug symbol table generated by the -g debug flag.

Using the Spring Container

If you’re using the Spring framework, and are using XML configuration files, you might need to use the -g debug flag when compiling. This will make the constructor parameter names available for dependency injection if you want to use name matching.

Using a Java Decompiler

The javap disassembler is very low-level and not very useful unless you know how to read Java p-codes. Java decompilers are far more useful. You can use them if you need to retrieve lost source code, or if you just want to see what code the compiler has automatically generated for you e.g. for auto-boxing, generics, enums, and enhanced for-loops.

You can play around with six free open-source decompilers at Upload a complied class file and decompile using any of the decompilers. Recompile your code using the -g debug flag, and upload it again. You’ll see the original local variable and parameters names, instead of auto-generated placeholder names.

I’ll tell you more about using a decompiler in another Java tip.

Sign up to get our weekly Java tips.

Leave a Comment

Your email address will not be published. Required fields are marked *