Way2Java

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.

public class Demo
{
  static final String str =  "Hello";
  public static void main(String args[])
  {
    // str =  "world";                // gives error
    System.out.println(str);     // called without the help of an object
    System.out.println(Demo.str);// called with class name
  }
}



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.

              static final String str =  "Hello";
              final static String str =  "Hello";

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

                    Demo d1 = new Demo();
                    d1.str =  "World";

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";