yesterday(April 5th 2012) i'am trying comparing string which is in environment:
computer 1
computer 2
computer 3
This is the code i'am trying
public class TComp{
public static void main(String[] args){
String a = "arif";
String b = "arif";
if(a==b){
System.out.println("match!");
}
}
}
As far as i know, to compare string in java we should using .equal() function and '==' will do interning in this case. But with those all computer with different OS, why intern work fine in computer 1, while i got error in computer 2 and computer 3?
please correct if any kind of word i've wrong. thank you.
In the same class, all string constants are folded into the .class
file constant pool by the compiler (at compile time). This means the compiler will only store one copy of the string (because who needs two identical constants in the pool?).
This means that within a class, ==
comparison of strings often works; however, before you get too excited, there is a good reason you should never use ==
comparison of strings. There is no guarantee that the two strings you compare both came from the in-class constant pool.
So,
"foo" == new String("foo")
is entirely likely to fail, while
"foo" == "foo"
might work. That might depends heavily on the implementation, and if you code to the implementation instead of the specification, you could find yourself in for a very nasty surprise if the implementation changes because the specification doesn't actually require that implementation.
In short, use .equals(...)
for Object
comparison, every time. Reserve ==
for primitive comparison and "this is the same object instance" comparison only. Even if you think that the two Strings
might be interned (or the same object), as you never know when you will be running under a different classloader, on a different JVM implementation, or in a machine that simply decided to not intern everything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With