-1
public class HelloWorld{

    public static void main(String []args){
        String a= "hello";
        String ab= a +"John";
        String abc = "helloJohn";
        System.out.println(ab==abc);

    }
}

It prints ab==abc false. Shouldnt it be true..??

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
Mozif Beigh
  • 109
  • 1
  • 1
  • 8
  • 1
    you need to study more about == and equal method. – ankush yadav Jun 24 '16 at 07:24
  • you new guys should google before posting the question. – ankush yadav Jun 24 '16 at 07:28
  • 1
    I think his point is not comparing the value, he is rather asking why `abc` is not the same reference as `ab`! Since I cannot post an answer I'll explain it here: Because Strings are immutable, when using `+` operator to concatenate two strings, a new String is created. That's why the comparing the reference (using `==`) returns `false`. – eol Jun 24 '16 at 07:32

3 Answers3

0

You should use for String equals/equalsIgnoreCase. '==' compares objects, NOT VALUES. Because when you make String a = "aa" means you create new object.(like new String("aa")). In java there're equals() and hashCode() methods inherited from Object class, but you may override them.

Ivan
  • 992
  • 1
  • 10
  • 22
0

Use yourStringVar.equals(anotherString) to check if they contain the same sequence of character, use == to check if they refer to the same object.

Falla Coulibaly
  • 759
  • 2
  • 11
  • 23
0

In java, String is an object, so two String-objects which have same content will not be equal (because those are different objects), hence abc == ab is not true. But there are methods to compare the contents of String objects. These are:

abc.equals(ab)

or

abc.compareTo(ab) == 0