public class HelloWorld { public static void main(String[] args) { String s1 = "Coding"; String s2 = "Coding"; String s3 = new String("Coding"); System.out.print(s1 == s2); System.out.print(" "); System.out.print(s1 == s3); }}Options: Pick one correct answer from belowtrue falsetrue truefalse falsefalse true
Question
public class HelloWorld { public static void main(String[] args) { String s1 = "Coding"; String s2 = "Coding"; String s3 = new String("Coding"); System.out.print(s1 == s2); System.out.print(" "); System.out.print(s1 == s3); }}Options: Pick one correct answer from belowtrue falsetrue truefalse falsefalse true
Solution
The correct answer is "true false".
Here's why:
In Java, when you compare two objects using the '==' operator, it checks whether they refer to the exact same object, not whether they are "equal" in a logical sense.
In the given code, s1 and s2 are both referring to the same object in the String constant pool, so s1 == s2 is true.
However, s3 is created as a new String object in heap memory, not in the String constant pool. So, even though the content of s3 is the same as s1 and s2, it's not the same object. Therefore, s1 == s3 is false.
Similar Questions
What will be the output?public class Test{ public static void main(String[] args){ int x=10, y=0; if(x && y){ System.out.print("TRUE"); } else{ System.out.print("FALSE"); } }}FALSETRUECompilation ErrorRuntime Error
What will be the output of the program?class Test { public static void main(String [] args) { Test p = new Test(); p.start(); } void start() { boolean b1 = false; boolean b2 = fix(b1); System.out.println(b1 + " " + b2); } boolean fix(boolean b1) { b1 = true; return b1; }}true truefalse truetrue falsefalse false
Which are printed out?public static boolean gtr(int num) { System.out.print("gtr"); return num > 3;}public static boolean lss(int num) { System.out.print("lss"); return num < 5;}public static void main(String[] args) { if (gtr(5) && lss(3)) { System.out.print("True"); } else { System.out.print("False"); } }
What will be the output of the following Java program?class mainclass { public static void main(String args[]) { boolean ct1 = true; boolean ct2 = false; if (ct1) System.out.println(ct1); else System.out.println(ct2); } }Options10truefalse
Find the output of the below Java program?public class Test { public static void main(String[] args) { Test t1 = new Test(); Test t2 = t1; System.out.println(t1.equals(t2)); }}A) trueB) falseC) nullD) error
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.