Declare a Constant String in Java

This tutorial demonstrates how to declare a constant string in Java.
Declare a Constant String in Java
A constant string is declared when it is required to be immutable, which means once any data is defined as constant, it cannot be changed.
Constant strings are declared as private static final String
in Java. These strings are initialized in the class and used in the different methods.
Example 1:
public class Constant_String {
//Declaring a Constant String
private static final String DEMO="Welcome To Delftstack!";
public static void main(String args[]){
//Print the Constant String
System.out.println(DEMO);
}
}
The code above declares DEMO
as a constant string that cannot be changed again.
Output:
Welcome To Delftstack!
If we try to re-declare the constant string, Java will throw an error in the output.
Example 2:
public class Constant_String {
//Declaring a Constant String
private static final String DEMO="Welcome To Delftstack!";
public static void main(String args[]){
//Print the Constant String
System.out.println(DEMO);
//Re-declare the constant string
DEMO = "The String is Re-declared";
System.out.println(DEMO);
}
}
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The final field Constant_String.DEMO cannot be assigned
at Constant_String.main(Constant_String.java:9)
The final
keyword always prevents data from being redefined. We can also declare other data types as constants.
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
LinkedIn FacebookRelated Article - Java String
- Perform String to String Array Conversion in Java
- Remove Substring From String in Java
- Convert Byte Array in Hex String in Java
- Convert Java String Into Byte
- Generate Random String in Java
- The Swap Method in Java