Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 691
John Allison Avatar asked Dec 04 '18 05:12

John Allison


1 Answers

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);
like image 199
GBlodgett Avatar answered Sep 18 '22 17:09

GBlodgett