Tuesday, November 30, 2010

Java final String optimisation

Some times I need a sub string of a string and I noticed that if you add final keyword, Java compiler makes a small optimization, isn't it?

For example :

String name = "this is a simple string";
String simple = name.substring(0,4);

Here Java creates two strings
but if you write this code in different way you get rid of one extra allocation

final String name = "this is a simple string";
final String simple = name.substring(0,4);

Both objects points to the same memory block and String object itself has a constant context
Am I right?

I am not sure about this conclusions, so, I will check it again when I have time.

If you know something how to use final for Strings and what exactly java compiler does, 

I'll be pleased if someone share his knowledges in this area

No comments: