Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string "==" in java check the reference, why this code return true? [duplicate]

Tags:

java

Possible Duplicate:
If == compares references in Java, why does it evaluate to true with these Strings?
String comparision with logical operator in Java

public static void main(String[] args) 
{
  String a = "ab";
  final String bb = "b";
  String b = "a" + bb;
  System.out.println(a == b);
}

why it print true??

but,

public static void main(String[] args)
{
  String a = "ab";
  String bb = "b";
  String b = "a" + bb;
  System.out.println(a==b);
}

it print false.

like image 219
HiMing Avatar asked Sep 26 '11 11:09

HiMing


1 Answers

You're seeing the result of two things working in combination:

  1. The compiler is processing the "a" + bb at compile-time rather than runtime, because the bb is final and so it knows it can do that. (There are other times it knows that, too.)

  2. All strings generated by the compiler are interned. For more about interning, see this answer to another StackOverflow question about == in Java.

So the result is that a and b point to the same string instance, and so == returns true.

like image 143
T.J. Crowder Avatar answered Sep 30 '22 17:09

T.J. Crowder