What will be the output of the following program?
public class Test{
public static void main(String args[]){
String s1 = "java";
String s2 = "java";
System.out.println(s1.equals(s2));
System.out.println(s1 == s2);
}
}
public class Test{
public static void main(String args[]){
String s1 = "java";
String s2 = "java";
System.out.println(s1.equals(s2));
System.out.println(s1 == s2);
}
}
A. false true
B. false false
C. true false
D. true true
Answer: Option D
Join The Discussion
Comments ( 11 )
Related Questions on Strings
In Java, which class is used to represent a sequence of characters as a string?
A. String
B. StringBuilder
C. StringSequence
D. StringArray
What is the correct way to create a new empty String object in Java?
A. String emptyString = "";
B. String emptyString = new String();
C. String emptyString = " ";
D. String emptyString = null;
E. Both A and B
Which of the following methods is used to compare two strings for equality in Java?
A. equals()
B. compareTo()
C. equalsIgnoreCase()
D. compare()
In 5th line = java equals java //true
in 6th line = java == java //true
so the answer will be (D) true true
as "java" is string literal and it will be stored in string literal pool .and when second "java" added it will be checked in string literal pool if present .and it is present hence will not be overwritten rather same pointer will be returned back to s2 as well .as we know == goes by reference equality and equals goes by content as both reference and content are same hence both true true
in this program string is letral and while content is same so .equals method and == operator is give same output .And letral always present in string constant pool.in this program not create a new object.
.equals and == are the same thing
s.equals(s2) checks for values so both r same i.e. java and java
hence it is true
s1==s2 checks for references here we haven't used new keyword so both will go to constant pool but in constant pool duplicates are not allowed hence references of s1 and s2 will same
hence answer is true true
answer will be truetrue
The answer will be true true.
The option displayed is wrong.
Correct answer is option d.
Here we didn't use new to create string just say as String s1=" java"; like this only.whenever we say like this memory is created in constant pool.In constant pool duplicates are not allowed it means s1 holds java s2 also holds java so equals checks it has same content or not. And == checks it has same address or not .obviously it has same address .
== compares the objects referencing to same literals or not that why true true is the anwer
Why is the bottom statement true? is not the double equal sign a comparison of reference and not the characters of the string object?