9
public static final String Test = "ABC";
public static String Test = "ABC";

Please show the difference between "final static String" and "static String" in java. except the final one can't be changed, What are the other differences? Thanks. when in more complex circumstances like multithreading and inherited, nothing changed?

sigh
  • 117
  • 1
  • 1
  • 4
  • 11
    That's what it means. End of story. – Ignacio Vazquez-Abrams Jan 07 '13 at 04:57
  • Yeah nothing more. Except it increases the code readability. – Vamsi Mohan Jayanti Jan 07 '13 at 05:00
  • @VamsiMohanJayanti What? Using `final` produces different behavior. What does it have to do with readability? – ApproachingDarknessFish Jan 07 '13 at 05:03
  • when in more complex circumstances like multithreading and inherited ..... – sigh Jan 07 '13 at 05:13
  • @ValekHalfHeart. Yes you can easily figure out the read only references and focus on the rest. There are some threads where it is already discussed. http://stackoverflow.com/questions/4279420/does-use-of-final-keyword-in-java-improve-the-performance , http://stackoverflow.com/questions/500508/why-should-i-use-the-keyword-final-on-a-method-parameter-in-java , http://programmers.stackexchange.com/questions/108349/why-is-the-final-keyword-used-so-little-in-the-industry – Vamsi Mohan Jayanti Jan 07 '13 at 07:40

14 Answers14

9

Although below description taken from Android doc, but might help for this Java tagged question.

Consider the following declaration at the top of a class:

static int intVal = 42;
static String strVal = "Hello, world!";

The compiler generates a class initializer method, called , that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal. When these values are referenced later on, they are accessed with field lookups.

We can improve matters with the "final" keyword:

static final int intVal = 42;
static final String strVal = "Hello, world!";

The class no longer requires a method, because the constants go into static field initializers in the dex file. Code that refers to intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive "string constant" instruction instead of a field lookup.

Note:

This optimization applies only to primitive types and String constants, not arbitrary reference types. Still, it's good practice to declare constants static final whenever possible.

Hope this will clear.

More details at UseFinal

Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
7

When it comes to variable

  • final Static String - constant and it is class variable
  • static String - class variable and not a constant
3

here's more

static final String s1;
static String s2;

line 1 does not compile, line 2 compiles

and there's more for primitive types.

final int x = 1;

void x() {
    int y = x + 1;
}

bytecode

ICONST_2
ISTORE 1

it means int y = 2 because x is a constant (though it's not static)

if we change

int x = 1;

bytecode

ALOAD 0
GETFIELD Test1.x : I
ICONST_1
IADD
ISTORE 1

JVM reads x and computes y

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

According to wiki

If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.

However since String is immutable to begin with, the difference is irrelevant in this case, and it is just a variable that cannot be modified in anyway.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
1

You said it yourself: the final one cannot be assigned. As far as I know, the final modifier provides o other behavior other than that one. The only thing I can think of is that as Test is public, static, and final, the compiler will automatically replace all occurrences of Test in your code and replace it with the String Literal "ABC", although as the String will be interned it will not have any effect on the code. Basically, final prevents the String from being assigned to a different reference, that is all.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
1

A final class can not be subclassed. It's like the sealed class in C#.

A final method can not be overridden.

A final field can only be initialized/assigned once, like a constant, but may not be necessarily known at compile time.

A static member is shared over all instances of a class.

So, static final is usually for something you never change again, but not necessarily hard coded at compile time.

Richard Dong
  • 704
  • 1
  • 7
  • 13
1

The compiled java class results in faster performance when Declaring a java variable as static final.

Check This

Sunil Gulabani
  • 878
  • 1
  • 8
  • 21
0

Final variables are instance variables, whose values cannot be changed after it is initialized.

But Static variables belongs to a class. This 'll be shared among all instances. So when you change the value of a static variable in an instance it gets reflected in all the instances.

Gnik
  • 7,120
  • 20
  • 79
  • 129
0

You can't change final's reference as below

public static final String Test1 = "ABC";
public static String Test2 = "ABC";
public static void testFinal()
{
    Test2 = Test1; //ok
    Test1 = Test2; //fail
}
slggamer
  • 217
  • 1
  • 2
0

A string can be declared both static and final. The advantages of declaring string with the both access specifiers are narrated hereunder.

The advantages are inclusive of both the affects of final and static.

  1. A string declared final cannot be reassigned. The string works as a constant.

  2. A string declared static can be called without the help of an object or with class name..

  3. A static variable does not maintain encapsulation. Declaring a static variable as final, no object can change the value but can access it.

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

The first statement in the main() method gives error as string str is declared as final.

The following statement raises compilation error as string str is declared as final.

Demo d1 = new Demo();
d1.str =  "World";

Realtime example

static final String truth = "Sun rises in the east";

Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
0

Here you go:

1) final static String: When you say final it's a constant and you can not alter it's value throughout the program. It's not a variable, you can not change it's value. In Java we use final keyword to declare constants. We are supposed to follow all uppercase with underscores to separate the words while declaring constants. For e.g.: MAX_INPUT_TIME, CONNECTION_POOL_SIZE, MAX_USER etc.

2) static String: You can use static for member variables of a class and not for local variables. Static variables are static and are accessible even w/o creating a instance of the class. So you can use them either by object.<static_variable_name> or ClassName.<static_variable_name>. They are accessible and hold the same value for all instances of the class.

For e.g.:

Class A {
  static int counter;  // it will be default to 0
}

Now while using this class:

System.out.println(A.counter);  // output: 0
A.counter++;
System.out.println(A.counter);  // output: 1
// Declare an instance of class A
A o1 = new A();
o1.counter++;
System.out.println(o1.counter);  // output: 1
// Declare another instance of class A
A o2 = new A();
System.out.println(o1.counter);  // output: 1  
# You still get it one and not 0, if it was non-static you would get it as 0;

Here, for example you can use static variables for the purpose of keeping track on number of objects created by putting a counter increment in constructor itself.

deej
  • 2,536
  • 4
  • 29
  • 51
  • I haven't compiled this code but it should give you a fair idea about what is difference and concept of both. – deej Jan 07 '13 at 05:33
0

I think there is no other difference between them in case of strings.

In case of multithreading, what is suggested is we should try to make objects immutable so that there's no risk of un-desirable state changes in the objects' states (due to improper synchronization or to avoid synchronization overhead).

final keyword (at various place like class, fields, methods) helps in achiving immutability if used properly but Strings are by default immutable.

In case of inheritence, final methods can not be overridden, but again this is not the case here.

vishal_aim
  • 7,636
  • 1
  • 20
  • 23
0

final Static String - constant and it is class variableit can be accessed but can't changed from any class static String - class variable and not a constant, it can be accessed and changed from any class

Puneet
  • 611
  • 6
  • 22
  • In case of string class, to make String class Immutable, this is by default Final, if you think on Architecture level, we maintain String pool and many reference refer to a single String object, when we need to change value any of them, JVM create a new object with new reference and rest ref. refer to the same object – Puneet Jan 07 '13 at 06:05
0

I think the first statement is often used to define a String constant. And the constant variable name is recommended to be "TEST" instead of "Test".

public static final String TEST = "ABC";

The second statement is seldom used for a good reason. It can cause concurrency issue in multi-thread context. We can have private instance String field in our class:

private String test = "ABC";

Hope this helps!

Jacky
  • 8,619
  • 7
  • 36
  • 40