Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final variable

 
Calanthe Wei
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
see the code below:

the result is:
final = final
Initialization of Loaded
non-final = non-final
And when I add change a little bit in the last sentence, like
public static final String y = "non-final";
the result is:
final = final
non-final = non-final
I am a little confused about these two results, can someone
explain it to me? thanks
regds,
Calanthe

[This message has been edited by Marilyn deQueiroz (edited November 10, 2001).]
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13055
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand where the problem is - since your program does not attempt to change the value of a final variable, the modifier has no effect.
Bill
 
Fei Ng
Ranch Hand
Posts: 1244
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by William Brogden:
I don't understand where the problem is - since your program does not attempt to change the value of a final variable, the modifier has no effect.
Bill

William, it is the output. On the second output the
"Initialization of Loaded" is gone.
the result is:
final = final
Initialization of Loaded
non-final = non-final
And when I add change a little bit in the last sentence, like
public static final String y = "non-final";
the result is:
final = final
non-final = non-final
 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One of reasons that triggers a class initialization is
when a static field declared by it is used and the reference
is not a compile time constant. Reference to a comiple-time
constant is resolved at compile time. Its use never cause initialization. (see JLS 12.4.1)

The declaration
public static final String x = "final";
makes x a compile-time constant. (see JLS 15.28)
That's why does not cause initialization of class Loaded.
It's the next statement that causes the initialization.
Similarly, when you change to static final, it becomes a compile-time
constant. So, class Loaded is not initialized.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
it was a useful tip.
thanks
maulin
 
Fei Ng
Ranch Hand
Posts: 1244
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
agree with Maulin, Vasavada..

hehehe..
 
Calanthe Wei
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you guys.
I got it.
Calanthe
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic