CursedChico
CursedChico

Reputation: 581

Final static can be changed?

I wrote my code but now i am trying to change to see what is happening.

In the object class field,

static final String msg="here";

And in the same object, in a methot

public void givemessage(int no)
{
    System.out.println("look.");       
    System.out.println(msg);
}

here it gives "here" when i call from main. But

public void names(String[] names)
{
    String msg=" - ";
    System.out.println(msg);
}

Here when i call from main it gives -, not "here" BUt it was final static. Why did it change and why is there no compile error? Or i misunderstood all java?

Upvotes: 3

Views: 197

Answers (7)

M Sach
M Sach

Reputation: 34424

String msg=" - "; is a local variable stored in stack whereas static final String msg="here"; is a class level variable stored in permgen space till java 6(stored in heap in java7). In nutshell you are referring two different variables here

Upvotes: 1

Philipp Sander
Philipp Sander

Reputation: 10249

it did not change.

in this snippet, your accessing the local variable.

public void names(String[] names)
{
    String msg=" - ";
    System.out.println(msg);
}

if you want to access the static field:

System.out.println(ClassName.msg);

Upvotes: 1

Korgen
Korgen

Reputation: 5409

This is called shadowing... the String which is passed to System.out.println is the one you defined within your names method as it has a tighter scope as the one on class level. Check this out http://en.wikipedia.org/wiki/Variable_shadowing

Upvotes: 4

mthmulders
mthmulders

Reputation: 9705

It did not change. You've "hidden" your static final member behind the local variable. The static final variable still has the old value - you can access it using XXX.msg, where XXX is the name of your class.

Upvotes: 1

AllTooSir
AllTooSir

Reputation: 49432

You are defining a local variable named msg inside the names() method . It is not the same as the static final class method. The local variable inside the method hides the class variable.

Upvotes: 1

Reimeus
Reimeus

Reputation: 159854

msg is a local variable in the names method. It doesnt change the variable at class level.

Upvotes: 2

morgano
morgano

Reputation: 17422

You are using two different variables, the class variable is immutable (final) but the local one is not, they have the same name but they are not the same.

If you want to verify this, put in your main method something like MyClassName.msg="-" and you'll see the compiler will complain.

Upvotes: 8

Related Questions