Static Final String Java

Static Final String Java

Static Final String Java: A string can be declared both static and final. The advantages of declaring string with the both access specifiers are narrated hereunder.

The advantages are inclusive of both the affects of final and static.

1. A string declared final cannot be reassigned. The string works as a constant.

2. A string declared static can be called without the help of an object or with class name..

3. A static variable does not maintain encapsulation. Declaring a static variable as final, no object can change the value but can access it.

Static Final String
Output screen on Static Final String Java

The first statement in the main() method gives error as string str is declared as final. More about static and final are explained earlier.

Note: The order of access specifiers is not important. Both the following are correct.

The following statement raises compilation error as string str is declared as final.

Some Realtime examples

static final String rate = "$rate is Rs.44.8";
static final String truth = "Sun rises in the east";
static final String center = "FlowLayout.LEFT aligns components to left";

6 thoughts on “Static Final String Java

    1. S. Nageswara Rao, Corporate Trainer Post author

      String is designed to be immutable. To have mutable string, StringBuffer is introduced. StringBuffer methods are thread-safe as all the methods are synchronized and best suitable in a multithreaded environment. To have unsynchronized methods, StringBuilder was introduced from JDK !.5.

Leave a Reply

Your email address will not be published. Required fields are marked *