yesterday(April 5th 2012) i’am trying comparing string which is in environment:
computer 1
- Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11D50b)
- OS X 10.7.3
computer 2
- Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11D50b)
- Window 7
computer 3
- Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11D50b)
- Linux Ubuntu 11.10
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
.classfile 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,
is entirely likely to fail, while
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(...)forObjectcomparison, every time. Reserve==for primitive comparison and “this is the same object instance” comparison only. Even if you think that the twoStringsmight 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.