-5

In this program all System.out.println(); gives true value. Can anyone explain in brief please?

public class Lab {

    public static void main(String args[]) {
        Stud st = new Stud("Vj");
        Emp em = new Emp("Vj");
        System.out.println(st.snm == em.enm);//How this Statement gives true
        st.show(em);
    }
}

class Stud {
    String snm;
    Stud(String snm) {
        this.snm = snm;
    }
    void show(Emp em) {
        String msg = "Vj";
        System.out.println(em.enm == msg);
        System.out.println(em.enm == snm);
        em.display(this);
    }
}

class Emp {
    String enm;
    Emp(String enm) {
        this.enm = enm;
    }
    void display(Stud st) {
        String
        var = "Vj";
        System.out.println(st.snm == var);
        System.out.println(st.snm == enm);
    }
}

1 Answers1

2

By defining and assigning string literal, you are storing/retrieving the string from string pool.

So when you do:

 String str1 = "abc";
 String str2 = "abc";
 System.out.println(str1 == str2);//will return true

It will return you true since two literals are equal.

== on two reference types is a reference identity comparison. Two objects that are equals are not necessarily ==. It is usually wrong to use == on reference types; most of the time equals need to be used instead:

str1.equals(str2)
Blacklight
  • 3,809
  • 2
  • 33
  • 39
SMA
  • 36,381
  • 8
  • 49
  • 73
  • @SMA..Thanks...I am explaining my question again..what doubt i have..Please clearify it....Stud class have one refrence variable String snm and Emp class have one refrence variable String enm, Inside main method I have created Stud class object st and passing "vj" in costructor same i did with Emp class where object is em...Now i want to compare (st.snm==em.enm),it gives true value....explain in brif ..Please..! – Ujjawal Singh Apr 14 '15 at 08:52
  • @UjjawalSingh He did explain in brief. Please try to understand it. Also look at the link in the comments. – Blacklight Apr 14 '15 at 09:08
  • @Ujjawal Singh: a value of `true` signals that the two values are identical, that’s the purpose of the `==` operator. – Holger Apr 14 '15 at 09:10