[1476] in java-interest
Re: Local variables can't be final?
daemon@ATHENA.MIT.EDU (prepapol@lifl.fr)
Tue Sep 5 19:15:20 1995
From: prepapol@lifl.fr
Date: Tue, 5 Sep 95 18:51:40 +0200
To: java-interest@java.sun.com, java@java.sun.com, edanuff@protagonist.com
Ed Anuff writes :
|-Are local variables allowed to be declared as final? The compiler doesn't
|-complain about the following code:
|-
|-
|-class FinalTestApp {
|- public static void main (String args[]) {
|- final int x = 5;
|- x = 10;
|- System.out.println(x);
|- }
|-}
|-
|-I expected that x would be a constant and its value would not be able to be
|-changed, but this doesn't seem to be the case.
|-
|-Ed
|-
|-
|-Ed Anuff
|-edanuff@protagonist.com
|-http://www.protagonist.com/
|-
|-
|--
|-Note to Sun employees: this is an EXTERNAL mailing list!
|-Info: send 'help' to java-interest-request@java.sun.com
|-
Hi Ed,
I've try your code and look at the doc "java language specification". So It seem to me that
a final variable must be a constant ! When you declare a final variable there is an only
memory emplacement which is shared by all the instantiations of this class (see "Java language
environnement" page 26 Part "Static and Final ...").
I've try some changes from your code to see the behaviour of a final variable and I've noted from
the above code :
class FinalTestApp {
public static void main (String args[]) {
Cste C1= new Cste();
Cste C2= new Cste();
C1.modifier();
C2.x = 10;
System.out.println("C1.x= "+C1.x);
System.out.println("C2.x= "+C2.x);
}
}
class Cste {
final int x = 5;
void modifier() {
final int y= 7;
//x= 20; final.java:19: Can't assign values to final variables: x
y= 70;
System.out.println("y= "+y);
}
}
1. When you try to change a final variable across a method => ERROR see x=20.
2. The statement C2.x=10 produce no error and the result is 5 ! (it's abnormal)
3. You can change the value in local (see "y" like your java code and it's not very clean)
------------------------------------------------
Bruno CUVELIER e-mail: prepapol@lifl.fr
Universite des Sciences et Technologies de Lille
Cite Scientifique
U.F.R. d'IEEA, batiment M3
59655 Villeneuve d'Ascq CEDEX.
FRANCE
------------------------------------------------
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com