Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is it possible using "==" when comparing string, java 1.6.0_29, osx?

Tags:

java

yesterday(April 5th 2012) i'am trying comparing string which is in environment:

computer 1

  1. Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11D50b)
  2. OS X 10.7.3

computer 2

  1. Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11D50b)
  2. Window 7

computer 3

  1. Java(TM) SE Runtime Environment (build 1.6.0_29-b11-402-11D50b)
  2. 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.

like image 365
Arif Setyawan Avatar asked Feb 20 '23 22:02

Arif Setyawan


1 Answers

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.

like image 143
Edwin Buck Avatar answered Mar 30 '23 01:03

Edwin Buck