Defining constant string in Java?

JavaString

Java Problem Overview


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 Solutions


Solution 1 - Java

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.

Solution 2 - Java

It would look like this:

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

If the constants are for use just in a single class, you'd want to make them private instead of public.

Solution 3 - Java

public static final String YOUR_STRING_CONSTANT = "";

Solution 4 - Java

We usually declare the constant as static. The reason for that is because Java creates copies of non static variables every time you instantiate an object of the class.

So if we make the constants static it would not do so and would save memory.

With final we can make the variable constant.

Hence the best practice to define a constant variable is the following:

private static final String YOUR_CONSTANT = "Some Value"; 

The access modifier can be private/public depending on the business logic.

Solution 5 - Java

You can use

 public static final String HELLO = "hello";

if you have many string constants, you can use external property file / simple "constant holder" class

Solution 6 - Java

Or another typical standard in the industry is to have a Constants.java named class file containing all the constants to be used all over the project.

Solution 7 - Java

simply use

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

the main part of this instruction is the 'final' keyword.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncsssView Question on Stackoverflow
Solution 1 - JavaderekerdmannView Answer on Stackoverflow
Solution 2 - JavaErnest Friedman-HillView Answer on Stackoverflow
Solution 3 - JavaRePROView Answer on Stackoverflow
Solution 4 - JavaPritam BanerjeeView Answer on Stackoverflow
Solution 5 - Javauser1190541View Answer on Stackoverflow
Solution 6 - JavaV_SinghView Answer on Stackoverflow
Solution 7 - Javamohsen kamraniView Answer on Stackoverflow