when exactly are we supposed to use "public static final String"?
Asked Answered
D

14

64

I have seen much code where people write public static final String mystring = ... and then just use a value.

Why do they have to do that? Why do they have to initialize the value as final prior to using it?

UPDATE

Ok, thanks all for all your answers, I understand the meaning of those key (public static final). What I dont understand is why people use that even if the constant will be used only in one place and only in the same class. why declaring it? why dont we just use the variable?

Danialah answered 26/7, 2012 at 20:39 Comment(5)
when defining string as constant ..Keos
Regarding the update, it's just good practice (IMO). If you come back later and need to reuse the same value, you don't then need to define it and update the previous code.Ovotestis
Sure doing so has its benefits. But code such as public static final String TILDE_EQUAL = "~="; really upsets me. When can "tilde-equal" be anything other than ~=?Avril
@Avril - any generally-good guideline can be misused by people who don't understand the rationale, or who follow rules blindly because someone cursed them by incanting the magic spell "it's a best practice".Lineate
@Avril Given how the JVM concatenates and optimizes String literals I'm not sure it's necessary to use a String constant rather than a literal in the first place. That said, making something like BigInteger BIG_ONE = new BigInteger(1); isn't necessarily bad practice. It isn't necessary in Java for Strings due to how the language provides special support for them, but if every "~=" invocation created a separate String object and you did it in a bunch of loops, TILDE_EQUAL might be justified. In short, constants can have valid uses even when the identifier makes the value obvious.Nace
M
103

final indicates that the value of the variable won't change - in other words, a constant whose value can't be modified after it is declared.

Use public final static String when you want to create a String that:

  1. belongs to the class (static: no instance necessary to use it).
  2. won't change (final), for instance when you want to define a String constant that will be available to all instances of the class, and to other objects using the class.
  3. will be a publicly accessible part of the interface that the class shows the world.

Example:

public final static String MY_CONSTANT = "SomeValue";

// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT))

Similarly:

public static final int ERROR_CODE = 127;

It isn't required to use final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.

Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.

Furthermore using final may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.

Finally note that final will only make truly constant values out of primitive types, String which is immutable, or other immutable types. Applying final to an object (for instance a HashMap) will make the reference immutable, but not the state of the object: for instance data members of the object can be changed, array elements can be changed, and collections can be manipulated and changed.

Mada answered 26/7, 2012 at 20:40 Comment(8)
and also the Static means that can be access in an static way (that not need to instanced the class like new ExampleClass).Apps
Does compiler makes any optimization using final static variables? Like replacing references of final static variables with actual values.Accoucheur
Only use 'public' if it needs to be public. Prefer "not public" where that meets your needs.Lineate
@Lineate thanks for the comment, I've edited my answer to include your point in the list in the answerMada
@Accoucheur I know Java makes optimizations for Strings by serializing them into the same location in memory in some cases so it doesn't create a million String objects with the exact same value. I don't expect object creation to be inlined (this would generally hurt performance, not help it), but I don't know if the optimizer will turn primitive constants into literals or not. This seems within the capabilities of the optimizer to me, so I'd actually be surprised if it didn't auto-inline primitives.Nace
It may be worth mentioning that "final" only makes primitive types and pointers to immutable objects effectively constant in Java. For pointers to mutable objects, the variable (the pointer) is constant in that it will always point to the object you assigned it, but the object's value can still change. A final Set pointing to a HashSet is not "constant" in the usual meaning as the object's value can still change. In that case "final" only means that the Set variable will always point to that particular HashSet object (rather than another object, a TreeSet, null, etc.).Nace
Thanks @TrixieWolf it's a good addition to an old answer, I'll add the detailMada
@Mada Not to nitpick, but there are many immutable object types other than String. Instead of "and String which is immutable" I think what you mean is, "and immutable objects (e.g. String, Integer, BigDecimal, enums)". (Though technically enum fields could be changed, object equality for an enum is immutable.)Nace
B
12
  1. Static means..You can use it without instantiate of the class or using any object.
  2. final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:

      public class StringTest { 
               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(StringTest.str);// called with class name  
                 } 
             } 
    

Thanks

Broadbrim answered 5/4, 2014 at 22:49 Comment(0)
E
6

The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.

And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).

Hope it helps.

Eb answered 26/7, 2012 at 21:7 Comment(0)
C
4

static means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.

Usually it's best to use final when you expect it to be final so that the compiler will enforce that rule and you know for sure. static ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.

Consummate answered 26/7, 2012 at 20:43 Comment(1)
You can re-create a static member at any given time.Supervene
F
2

final indicates that the value cannot be changed once set. static allows you to set the value, and that value will be the same for ALL instances of the class which utilize it. Also, you may access the value of a public static string w/o having an instance of a class.

Fawcett answered 26/7, 2012 at 20:42 Comment(0)
P
2

public makes it accessible across the other classes. You can use it without instantiate of the class or using any object.

static makes it uniform value across all the class instances. It ensures that you don't waste memory creating many of the same thing if it will be the same value for all the objects.

final makes it non-modifiable value. It's a "constant" value which is same across all the class instances and cannot be modified.

Peggi answered 28/5, 2015 at 5:52 Comment(3)
I wouldn't agree with this part "You can use it without instantiate of the class or using any object." That's what static keyword is for.Supervene
" public makes it accessible across the other classes. You can use it without instantiate of the class or using any object." can you show an example for this part?Tiberius
Can we group-downvote that total misinformed answer? Or after all those years @nikhil learned enough to actually give advice and edit the answer?Ivyiwis
I
2

You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.

Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.

An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).

Here's why:

  1. Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
  2. What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.

What are the consequences?

Imagine you have this:

class Foo {
  public static final String VERSION = "1.0";
}

class Bar {
  public static void main(String[] args) {
    System.out.println("I am using version " + Foo.VERSION);
  }
}

After compiling and running Bar, you'll get:

I am using version 1.0

Now, you improve Foo and change the version to "1.1". After recompiling Foo, you run Bar and get this wrong output:

I am using version 1.0

This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.

I've seen this a couple of times and it is really hard to debug.

If by final you mean a constant that might change in later versions of your program, a better solution would be this:

class Foo {
  private static String version = "1.0";
  public static final String getVersion() {
    return version;
  }
}

The performance penalty of this is negligible, since JIT code generator will inline it at run-time.

Ivyiwis answered 9/8, 2019 at 4:1 Comment(0)
W
1

Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.

Wie answered 26/7, 2012 at 20:42 Comment(0)
M
1

Why do people use constants in classes instead of a variable?

readability and maintainability,

having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.

Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.

But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.

For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.

Macbeth answered 17/9, 2016 at 23:26 Comment(1)
the comedy is hard in this, nice:)Ivyiwis
R
0

public makes it accessible across other classes. static makes it uniform value across all the class instances. final makes it non-modifiable value. So basically it's a "constant" value which is same across all the class instances and which cannot be modified. With respect to your concern "What I don't understand is why people use that even if the constant will be used only in one place and only in the same class. Why declaring it? Why don't we just use the variable?" I would say since it is a public field the constant value can also be used elsewhere in some other class using ClassName.value. eg: a class named Math may have PI as final static long value which can be accessed as Math.PI.

Roping answered 17/2, 2015 at 19:7 Comment(1)
you are not answering the question. if you were told to create a class, why would you use that? once again, we all understand the key public,static, final... we all understand that we can access it ... . but in practise its not what is happening. the variable is declared and used in the class. i don't see why and how it s the best way to do itDanialah
S
0

It is kind of standard/best practice. There are already answers listing scenarios, but for your second question:

Why do they have to do that? Why do they have to initialize the value as final prior to using it?

Public constants and fields initialized at declaration should be "static final" rather than merely "final"

These are some of the reasons why it should be like this:

  1. Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.

  2. Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value owing to the behavior of the final field.

Sulphide answered 20/2, 2019 at 6:13 Comment(0)
S
0

This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.

In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.

Schleswig answered 8/1, 2021 at 10:51 Comment(1)
Not sure why this was down-voted. I think the answer is valid, but maybe confusing some terms - e.g. I think with "constant values" they mean "literal", and indeed it is a good practice to avoid using not-obvious literals, and instead use a variable (or constant) with a meaningful name.Lichenology
B
0

I think these are all clear explanations. But, Let me clarify it by giving a java inbuild example.

In java, most would have used System.out.println()

The system is a class and out is a PrintStream class.

So what java says is I will take care of the initialization of the out object(PrintStream) and keep the initialization private to myself in the System class.

public final class System {

    public final static PrintStream out = null;

    //Some initialization done by system class which cannot be changed as it is final.
}

You just access the println method statically without worrying about its initialization.

Beefburger answered 3/10, 2021 at 15:12 Comment(0)
V
0

Besides all the above reason, static final use a naming convention: all uppercase letters with underscores between words.

For example:

private static final int NUM_BRACKETS = 45;
private static final String TEMPLATE = "Hello";
Vellavelleity answered 4/9, 2023 at 16:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.