1

I have two program as shown below.

When i run both these program both working fine.

But the the first code have a two string when I compare it gives result "ok".

the second code also have two string but this gives result "no".Why?

class Stringimp {

      public static void main(String[] args) {

      String str = "ali";
      String s1="ali";
      if (str == s1) {
        System.out.println("ok");
      } else {
      System.out.println("no");
    }
 }

}

 class Stringimp {

       public static void main(String[] args) {

       String str = "ali";
       String s1="ALI";
       s1=s1.toLowerCase();
       if (str == s1) {
           System.out.println("ok");
       } else {
           System.out.println("no");
       }
  }

}

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
  • 2
    It's due to the internal handling of Strings by Java. You should always avoid _str1==str2_. Use _str1.equals(str2)_ instead. – blafasel Jun 22 '14 at 15:03
  • I agree with @blafasel's advice unless you really do want to ask "Are `str1` and `str2` either both null or both point to the same String object?". – Patricia Shanahan Jun 22 '14 at 15:06
  • As the question shows, it is hard to predict, when a new String object is produced or when an existing is "reused" (unless you use interning). Therefore I tend to to be somewhat more fundamental at this point. – blafasel Jun 22 '14 at 15:11

1 Answers1

0

Because you're comparing references, in the first, they refer to the same object, in the

second, they don't.

RAJIL KV
  • 399
  • 1
  • 7
  • 24
  • might want to mention that in first case java creates 1 string with the value during compilation and in 2nd case the fact that the to lower is run forces them to be 2 different objects with different references. – LhasaDad Jun 22 '14 at 15:38