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
  }
}


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.

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

6 thoughts on “Static Final String Java”

  1. if string is final why again static final String?cant we simply use static String instead of static final string?

    1. The sting class is designed as final and also strings are immutable. Even though immutable, still you can reassign a new value to string; but at the cost of performance. If you declare sting as final in your code, you cannot reassign a new value for it.

    1. 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 Comment

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