EDIT: I would love to read reactions to Steve Reed's AOP approach. Comments to his answer are encouraged!
I'm a novice, and at some point I realized it would be helpful to know the contents of a variable during program execution. So I started doing this:
EDIT: fixed this. Used to be: var + ": " + var, which was totally wrong. Dumb typo.
System.err.println ( "var: " + var );
Later I learned that this was common practice. At least, where a debugger was unavailable or unwanted.
I use a basic text editor, and typing the print statement every time I need to debug a variable is pretty tiresome, so I thought, why not something like this:
void dbug ( Object obj )
{
String variableName = obj.somehowGetVariableName();
String variableContents = obj.toString();
System.out.println ( variableName +": " + variableContents );
}
But apparently getting the variable name is easier said than done.
java-reflection-how-to-get-the-name-of-a-variable
Am I stuck with:
System.err.println ( "var: " + var );
Or is there a popular shorthand version of this?
What Is Print Statement Debugging? Print statement debugging is a process in which a developer instruments their application with “printf” statements to generate output while the program is executing. The output generated helps diagnose issues within the program.
Debugging with print statements Sometimes you just print little messages telling you where the program was executing, so you get a better idea of where the problem occurred. A print statement in Java looks like this: System. out. println("motor speed is " + motor.
A Java program can be debugged simply by right clicking on the Java editor class file from Package explorer. Select Debug As → Java Application or use the shortcut Alt + Shift + D, J instead. Either actions mentioned above creates a new Debug Launch Configuration and uses it to start the Java application.
The main advantage is that you can write your debug messages in the DEBUG level and when you deploy your code, you'll just configure the logger to skip those messages (instead of searching for all occurrences of System. out. println in your code).
The debugger is started with the jdb command; it attaches to the JVM using JPDA. The JVM starts up, but suspends execution before it starts the Java application.
I think that System.err.format is what you want:
System.err.format("var: %s\n", var);
is a shorthand for:
System.err.println(String.format("var: %s", var));
If you use IntelliJ IDEA, you can use the "Live template" shortcut for printing to System.out such as soutp (and then a TAB)
to debug the method parameters, soutv
to trace the name of a variable along with it's value, etc.
To read the list of shortcuts\modify it, go to File->Settings->Live Templates->Output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With