The output of the following fraction of code is
public class Test{
public static void main(String args[]){
String s1 = new String("Hello");
String s2 = new String("Hellow");
System.out.println(s1 = s2);
}
}
public class Test{
public static void main(String args[]){
String s1 = new String("Hello");
String s2 = new String("Hellow");
System.out.println(s1 = s2);
}
}
A. Hello
B. Hellow
C. Compilation error
D. Throws an exception
E. None of these
Answer: Option B
Solution(By Examveda Team)
The output of the given code will be:In the code, two String objects s1 and s2 are created with the values "Hello" and "Hellow" (note the typo in "Hellow"), respectively. Then, the System.out.println() statement prints the result of the assignment s1 = s2. This assignment sets the value of s1 to the same value as s2, which is "Hellow". As a result, the println statement prints the value of s1, which is "Hellow".
Join The Discussion
Comments ( 10 )
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()
Here they used s1=s2. So, we get output as Hellow.
If they give s1==s2.then, we may get false.
How it is possible, output should be false or true
string s2 is assigned to string s1.So now the s2 (Hellow) is now present in s1 and prints op asHellow
String is immutable.
So reference is allocated.
That what hellow is the answer
actually reference of s2 is being assigned to s1. there are Hellow is not being assigned to s1. reference of s2 is being assigned to s1. It means s1 lost its connection with Hello string and connects with Hellow
here the string s2="hellow" is being assigned to s1.hence s1="hellow" and
System.out.println(s2==s3);//hellow
what is happening actually here assignment operator(right to left associative)so value of s2 assign to s1 and print s1
s1 = s2. first, value of s2 it assign to s1 and it prints value of s1.
Why is this the case, would this not return an error?
Why is this the case, would this not return an error?