What is the output of following.

public static void main(String[]  args) {
    String s1="sanjay";
    String s2="sanjay";             
    System.out.println("c="+s1==s2);
}
  1. prasad

  2. true

  3. false

  4. compileTime Error


Correct Option: C

AI Explanation

To understand the output of the given code, let's go through each line:

String s1 = "sanjay";
String s2 = "sanjay";

In these lines, two String variables s1 and s2 are declared and assigned the same value "sanjay". Since string literals are stored in a common pool, both s1 and s2 will refer to the same object in memory.

Next, let's look at the following line of code:

System.out.println("c=" + s1 == s2);

In this line, the + operator is used to concatenate the string "c=" with the value of s1. Then, the == operator is used to compare the concatenated string with s2.

However, there is an issue with this line of code. The + operator has higher precedence than the == operator. Therefore, the expression "c=" + s1 is evaluated first. This results in a new string "c=sanjay".

Then, the == operator compares the string "c=sanjay" with s2. Since s2 also refers to the string "sanjay", the expression "c=" + s1 == s2 evaluates to false because the == operator compares the object references, not the string values.

Finally, the System.out.println() method is called with the resulting boolean value false as the argument, and the output is displayed on the console.

Therefore, the correct answer is:

C. false

Find more quizzes: