Hi All
here is question from
http://www.geocities.com/sun_guoqiao/scjp/mockexam2answer.html Question mock-exam-02-12:
What is the output of trying to compile and run the following code?
(Select one correct answer)
-----------------------------------------------------------------------
<pre>
public class Test012
{
public static void main(String args[])
{
String s0 = new String("Java");
String s1 = s0.trim();
String s2 = s0.substring(0, 4);
String s3 = s0.toString();
System.out.println(s0 == s1);
System.out.println(s0 == s2);
System.out.println(s0 == s3);
}
}
</pre>
-----------------------------------------------------------------------
A: The output is:
true
false
true
B: The output is:
true
true
false
C: The output is:
true
true
true
D: The output is:
true
false
false
answer is :
Answers:
: C
Explanation:
: Those method will return the String itself under
the circumstance given by the question.
I was thinking the answer will be
false
false
false
after seeing the answer I run the program and answer is correct.
My question is this. If as per
java doc http://java.sun.com/j2se/1.3/docs/api/java/lang/String.html#substring(int,%20int) substring() method of String class returns new String object then how come s0 , s2 pointing to same String litral.
(s3 == s0) true agreed.// as per Docs
(s1 == s0) true agreed (as per docs trim() method
Returns:
this string, with white space removed from the front and end.)
but with question. Then how can we say that String is
immutable ?
OK let us say ... yes, inernally JVM finds the String available in String pool so it just made other references to point to that litral and hence answer is true for all.
If this is the case then
<pre>
public class Test011128_012
{
public static void main(String args[])
{
String s0 = new String("java");
String y = new String("ava");
String s4 = s0.substring(1,4); // s4 will refer object containing "ava"
String s1 = s0.trim();
String s2 = s0.substring(0,4);
String s3 = s0.toString();
System.out.println("y == s4 : " + (y == s4) +" : s4 = "+ s4 + " ,y = "+ y +" \n");
System.out.println(s0 == s1);
System.out.println(s0 == s2);
System.out.println(s0 == s3);
}
}
</pre>
in above code why (y == s4) is not true as both string references should be pointing to same string object ??
So now I have two Questions:
1. How can we say that String object are immutable as trim returns *this* after removing spaces from string object.(contents of string being changed)
2. If substring() method is suppose to return new String object then how came (s2==s0) is true ?
Thanks in advance
------------------
Regards
Ravish
[This message has been edited by ravish kumar (edited November 28, 2001).]