-1

Here is what i am talking about:

package finalExample;

public class FinalExample {

public static void main(String args[]) {

    final String str1 = "str";
    final String str2 = "ing";

    String str11 = "str";
    String str22 = "ing";

    System.out.println("Using equals() for non final :" + str11.equals(str22));
    System.out.println("Using == for non final :" + (str11==str22));
    System.out.println("MAGIC Using == for non final :" + str11==str22);

    System.out.println("Using equals() for final :" + str1.equals(str2));
    System.out.println("Using == for final :" + (str1==str2));
    System.out.println("MAGIC Using == for final :" + str1==str2);
}

}

Output is:

Using equals() for non final :false
Using == for non final :false
false
Using equals() for final :false
Using == for final :false
false

Both MAGIC Statements are not printed. Why is it so?

Destructor
  • 3,154
  • 7
  • 32
  • 51
  • 1
    Actually, I deleted my answer. Based on the "tricky" nature of the question and the name of the class, this sounds suspiciously like a homework question... – yshavit Oct 17 '13 at 06:26
  • @yshavit Yeah, these are difficult to decide on. :-/ – chrylis -cautiouslyoptimistic- Oct 17 '13 at 06:27
  • @yshavit no it is not a homework question bro. I came across this all of a sudden while working, and i wanted to ask the reason so i wrote this example class and posted here. – Destructor Oct 17 '13 at 06:29
  • Alright, then cool and sorry to be suspicious. We get that a lot on SO, unfortunately. :( – yshavit Oct 17 '13 at 06:31
  • @Claudiu not exactly ! I know why are final and non final acting that way, but i wanted to know why is the MAGIC statement not printing. Still thanks for the link. :) – Destructor Oct 17 '13 at 06:31
  • [Operator Precedence](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html) – Aniket Kulkarni Oct 17 '13 at 06:33

3 Answers3

12

The + operator binds at a higher precedence than the == operator, so your expression is:

"MAGIC Using == for final :" + str1==str2
("MAGIC Using == for final :" + str1)==str2
(a new String object created for the comparison can't)==str2
false
chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
3

You are evaluating

"MAGIC Using == for non final :" + str11

which is a string, and then comparing with str2

djna
  • 54,992
  • 14
  • 74
  • 117
2

I think it did print. the result is false; so it prints "false" you can think it as: res = "MAGIC Using == for final :" + str1 ; println(res == str2) so it prints false.

Robin
  • 134
  • 9