This code
int a = 6;
System.out.print("The result is " + a*a);
works just fine, but this one
int a = 6;
System.out.print("The result is " + a^a);
produces an exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: at pkg1.pkg4.taking.input.TakingInput.main(TakingInput.java:11)
Why so?
The question arose when I was trying to print the results of several bitwise operations in one swoop, like so:
System.out.print(a&b + "\n" + a|b + "\n" + a^b);
I looked up the description of the print()
method and several topics on bitwise operators and printing to the console on SO including the recommended topics when composing the question, but couldn't find an answer.
This is because the +
has higher precedence than the ^
so it compiles to:
("The result is " + a) ^ a
Which obviously will not work. Put parenthesis around it:
System.out.print("The result is " + (a^a));
Or as Holger mentioned, you can eliminate this problem by using printf
:
System.out.printf("The result is %d", a^a);
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