aspose file tools*
The moose likes Beginning Java and the fly likes final variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "final variables" Watch "final variables" New topic
Author

final variables

Himanshu Jhamb
Ranch Hand

Joined: Aug 01, 2001
Posts: 134
Hi.
Pls. consider the following piece of code
public void f1()
{
String s="Hi";
//final String s="Hi";
}
Assuming I will need to initialize this variable 's' only once, inside f1(), and after that I just need to access its value, Is it a better idea to define this variable as a final variable ?
My concern is performance. In my opinion, it would probably be better to define it as a final variable. If its final, it would not be allocated memory as is normally allocated for an Object... instead, it would be stored in the String literal pool.
Am I correct ? Pls. comment.
thanks


Himanshu Jhamb<br />SCJP2 v1.2 (April 2002)<br />SCJP2 v1.4 (May 2002)
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Well if it is a String anyway, and it is initialized as a literal as you did above, then it gets stored in the String Pool ANYWAY since Strings are immutable. Just don't use the "new" keyword.
Making it final would just mean that you could never point at a different String, it will not improve the performance of this String.


"JavaRanch, where the deer and the Certified play" - David O'Meara
 
Consider Paul's rocket mass heater.
 
subject: final variables