Examveda
Examveda

What will be the output of the following program code?
class LogicalCompare{
        public static void main(String args[]){
                String str1 = new String("OKAY");
                String str2 = new String(str1);
                System.out.println(str1 == str2);
        }
}

A. true

B. false

C. 0

D. 1

E. Displays error message

Answer: Option B


This Question Belongs to Java Program >> Strings

Join The Discussion

Comments ( 8 )

  1. Paramesh Paramesh
    Paramesh Paramesh :
    7 months ago

    public static void main(String[] args) {: This is the main method, which serves as the entry point of the program.

    String s1 = new String("ok");: This line creates a new String instance with the content "ok" and assigns it to the variable s1.

    String s2 = new String(s1);: This line creates a new String instance with the content of the s1 variable ("ok") and assigns it to the variable s2.

    System.out.println(s1 == s2);: This line compares the references of s1 and s2 using the == operator. It checks whether both variables refer to the same memory location (i.e., if they are the same object).

    Since you're using the new keyword to explicitly create new String instances, even if the content is the same, the instances will be stored in separate memory locations. Therefore, the comparison s1 == s2 will result in false.

  2. Bikram Poudel
    Bikram Poudel :
    5 years ago

    Actually this gives compilation error as there is no quotation mark in str1

  3. Mounika Gutha
    Mounika Gutha :
    5 years ago

    By using new keyword new string will be created in heap area . if we compare those strings using double equals operator it will compare references here references is not same so it will return false

  4. Sumi Scaria
    Sumi Scaria :
    6 years ago

    == does comparison of objects, not its values. It will always return false unless both objects have same name. Thus inorder to compare equality of two string objects use equals() method.

  5. K DINESH
    K DINESH :
    7 years ago

    == operator compares the address not the content present in str1 and str2.for the str1 we used new so it creates some space in non constant pool like wise in str2 also we used new it creates some space in non constant pool itself.But for both str1 and str2 have different address .

  6. Smruti Panda
    Smruti Panda :
    7 years ago

    Because in non constant pool of string pool duplication is allowed so both the strings will be stored in different address and when we compare the address it will give us false.

  7. Examveda
    Examveda :
    8 years ago

    In java, == operator compares references not values.
    because str2 refers to instance created in nonpool and == operator compares references not value.

  8. Metier Techtutors
    Metier Techtutors :
    8 years ago

    Why output of that question is false while hash code and content of both strings are same?

Related Questions on Strings