this qusetion is from danchisholm mock questions....
class MWC114 {
public static void main(String[] s) {
String s1 = new String(ABCDEFG), s2 = new String(EFGHIJ);
String s3 = s1.substring(4,7), s4 = s2.substring(0,3);
System.out.println((s3 == s4) + (s3 + s4).equals(s4 + s3));
}}
What is the result of attempting to compile and run the program?
a. Prints: false,false
b. Prints: false,true
c. Prints: true,false
d. Prints: true,true
e. Compile-time error
f. Run-time error
g. None of the above
i have doubt that s3==s4 should return true
as s3= EFG
S4=EFG
therefore one obj is created in heap that is s3 and as per string pool concept..s4 should point to s3 in heap so ans should be true...please rectify if i m wrong as ans given is false true..
Well rohit your display name doesn't comply with the javaranch naming policy so please change it.
Secondly at javaranch if you post a question, then you have to Quote the Source of the question. So please tell us from where did you get this question so that we can help you...
Do you know the difference between == and equals() when used on objects (such as String objects)?
== does not check if the contents of two strings are the same - it only checks if both arguments refer to the exact same object. If you have two String objects, this will return false, even when the content of those String objects is the same.
Why do you think that s3 and s4 are referring to the same String object? (They're not).
ya..i know == will return true only if two reference points to same object
say ,
String s1= new String("hi");
String s2=s1
in this case it will return true...
but my question is String s3= "EFG";
String s4= "EFG;
now as per string pool concept, value "EFG" is passed to the string pool and object will be created in heap so s3 will point to string instance with value "EFG"...and when JVM encounters same literal again it does not create a new object but will point the it reference to the existing object(to which s3 points).please rectify if i am wrong with explanation.thanks
but as strings are immutable...therefore watever method you invoke on it its of no use unless you assign a reference to it...so here s3 is just a reference to new string instance with value ABCDEFG....but second time when you assign s4 to same value wont jvm assign s4 to the existing object with same value as per string pool...i know this a basic stuff and i am getting confuse in it...sorry for the trouble.