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?
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.
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 "" .
Luckily for us, String in Java is an immutable class, so a final String is const in both regards.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With