Bitwise operation not concatenating with string in print() in Java

  • A+
Category:Languages

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)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: