File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes final String Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "final String" Watch "final String" New topic
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: final String
 
Similar Threads
Doubt about final....
string question .explanation pls
Immutability of strings???
String constant pool??
New challenge equals == hashcode(m confused)