What would be the equivalent in java of C++ code:
#define printVar(var) cout<<#var<<"="<<var;
printing string value and its name .
What would be the equivalent in java of C++ code:
#define printVar(var) cout<<#var<<"="<<var;
printing string value and its name .
You can print the variable name since Java 8 version: Java Reflection: How to get the name of a variable?
You can print the value using something like: System.out.println(String.valueOf(var));
Through Java reflection you can get more information from a variable, such as class name, package name, class attributes, etc...
In Java there's no preprocessor directives, so in this case there's no option, except for using IDE's shortcuts for this (usually, "soutv + tab", this works, for example, in InteliJ IDEA and Netbeans). So you'll get the output for default template:
System.out.println("var = " + var);
Or you may implement the common method for doing this:
void printVariable (Object variable, String name) {
System.out.println (name + " = " + variable);
}
And run it in this way:
printVariable (var, "var");
printVariable (anotherVar, "anotherVar");
UPDATE: according to this answer, in Java 8 there might be a way to do it through reflection (in some cases)
Java doesn't have a standard pre-processor to do this. Generally this is a good thing. In this case, you can use you own.
I suggest you use the debugger in your IDE for debugging your program, this avoids the need to write code to dump such debug statements to the console. Note: in Java there is little penalty for making your code always debuggable and most code ships with debug on.
If you breakpoint a line you can see all the values for local variable and what ever objects they point to. You can also go down the stack and see all the callers if you want.
Usually you don't have preprocessing for Java. But a similar behaviour method would be:
public static void printVar(String var) {
System.out.print("var=", var);
}