Which is the safer method to define string constants

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

These are all examples of (compile time) constant expressions. The bytecode compiler (e.g. javac) will perform the concatenations so that there is a single string in the constant pool in the compiled “.class” file for the value assigned to sample1 and sample2. And the value of sample3 is also a compile time constant … since it is the concatenation of two other compile-time constant variables. The rules that determine what is or is not a constant expression are lengthy (JLS 15.28 and 4.12.4), but: string literals are, final variables of type String are, provided that they are initialized to a… Read more »

Jason
Guest

There is no difference. static variables are initialized whenever the class is first encountered. From a memory perspective, all 3 are equal since they load the same String into memory. The first option should be preferred simply because it is more readable.