Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining constant string in Java?

Tags:

java

string

I have a list of constant strings that I need to display at different times during my Java program.

In C I could define the strings like this at the top of my code:

#define WELCOME_MESSAGE "Hello, welcome to the server" #define WAIT_MESSAGE "Please wait 5 seconds" #define EXIT_MESSAGE "Bye!" 

I am wondering what is the standard way of doing this kind of thing in Java?

like image 993
csss Avatar asked Mar 09 '12 18:03

csss


People also ask

How do you define a constant string in Java?

Java doesn't have a special keyword to define a constant. const is reserved keyword (you can't use it as a name of a variable for example), but it's unused. So to declare a constant in Java you have to add static final modifiers to a class field.

How do you define a string constant?

String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: "This is a string." The null string, or empty string, is written like "" .

Is final string a constant in Java?

Luckily for us, String in Java is an immutable class, so a final String is const in both regards.

Can we declare constant in Java?

To turn an ordinary variable into a constant, you have to use the keyword "final." As a rule, we write constants in capital letters to differentiate them from ordinary variables. If you try to change the constant in the program, javac (the Java Compiler) sends an error message.


1 Answers

Typically you'd define this toward the top of a class:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server"; 

Of course, use the appropriate member visibility (public/private/protected) based on where you use this constant.

like image 128
derekerdmann Avatar answered Oct 13 '22 06:10

derekerdmann