• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final variables

 
Himanshu Jhamb
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic