| Author |
final String
|
Indraneel Das
Greenhorn
Joined: Oct 15, 2002
Posts: 5
|
|
Hi all i came accross the following question in one of the mock tests of Dan Chisholm: class test{ public static void main(String args[]) { String a = "A"; String b = "B"; final String c = a+b; final String d = a+b; System.out.print((c==c) + ","); System.out.print(((a+b)==(a+b)) + ","); System.out.print(c==d); } } Prints: true,false,false Now if both the variables a & b are declared as final, then why the output changes to true,true,true Thanx and Regards Indraneel
|
 |
Arpana Rai
Ranch Hand
Joined: Nov 12, 2002
Posts: 93
|
|
Originally posted by Indraneel Das: Hi all class test{ public static void main(String args[]) { String a = "A"; String b = "B"; final String c = a+b; final String d = a+b; System.out.print((c==c) + ","); System.out.print(((a+b)==(a+b)) + ","); System.out.print(c==d); } } Indraneel
a+b evaluates at runtime.so, everytime u execute a+b it returns new string object. that is why (a+b)=(a+b) prints false. But, in the below given code a and b are declared final.So, a+b evaluates at compile time and hence (a+b)=(a+b) prints true. hope it helps. regds Arpana
|
SCJP1.4(91%)
|
 |
Indraneel Das
Greenhorn
Joined: Oct 15, 2002
Posts: 5
|
|
Thx Arpana for clarifying my doubt. Now its clear to me. Regards Indraneel
|
 |
John Pritchard
Ranch Hand
Joined: Nov 15, 2002
Posts: 49
|
|
|
Given that a+b evaluates at runtime, does the JVM check the String pool to see if the result of the runtime calculation already exists or does it always return a new String?
|
John Pritchard<br />If a JTree falls in the woods, is it Observable
|
 |
Arpana Rai
Ranch Hand
Joined: Nov 12, 2002
Posts: 93
|
|
Originally posted by John Pritchard: Given that a+b evaluates at runtime, does the JVM check the String pool to see if the result of the runtime calculation already exists or does it always return a new String?
At runtime a+b (if a and b are not final ) returns new String object and the String constructor does not check the String pool when it creates a new String object. regds arpana
|
 |
 |
|
|
subject: final String
|
|
|