java - Why does ("str" + x == y) only compile for reference types? -
why == operator behave differently references primitive info types?.
string string1 = "mystring"; string string2 = "mystring"; int num1 = 10; int num2 = 10; system.out.println("value "+string1==string2); //works fine system.out.println("value "+num1==num2); //compile time error i unable figure out logical reason behind this. ps: brackets within print statements deliberately not used. :)
it's issue of operator precedence. sec print statement beingness interpreted as:
system.out.println(("value "+num1)==num2); // notice parenthesis which attempts compare string int, producing compile-time error. add together parenthesis solve problem:
system.out.println("value " + (num1==num2)); // compiles the precedence of java operators outlined in operators.
now, this:
// original: system.out.println("value "+string1==string2); // equivalent to: system.out.println(("value "+string1)==string2); works because "value "+string1 string itself, it's valid compare string2 ==.
java operator-keyword equality
No comments:
Post a Comment