*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes flow controls Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "flow controls" Watch "flow controls" New topic
Author

flow controls

Hasitha Randika
Ranch Hand

Joined: Sep 04, 2007
Posts: 50
class A{
final static int x2 = 7;
final static Integer x4 = 8;
public static void main(String ar[])throws Exception{
Integer x1 = 5;
String s ="a";
if(x1 < 9)
s += "b";
switch(x1){ //can we use a variable which is not assign as final
case 5: s += "c";
case x2: s += "d";
case x4: s += "e"; //error why?
}
System.out.println(s);
}
}
in the above syntax case4:s+="e" gives a compile error.how come?

and here in the switch condition it uses a variable.can we use a variable which is not assign as final
Vassili Vladimir
Ranch Hand

Joined: Mar 08, 2007
Posts: 1585
Hi,

The reference itself is final, but not its state. Meaning, x4 can not refer to another object in the heap, but this does not mean that its value can not change.

Best of luck ...


Vassili ...
SCJP 5.0, SCWCD 1.4, SCJA 1.0
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

The values you use in case statements in a switch block must be compile-time constants.

In the code above, x4 is not a compile-time constant. As Vassili says, the value of x4 itself is constant (it's always referring to the same object), but in principle the value of the object could change.

(Actually, the value of an Integer object never changes, because wrapper classes like Integer are immutable. But the Java compiler doesn't know that, so it's still illegal).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: flow controls
 
Similar Threads
Doubt from K&B ch 5
Switch Statement
mock question about "case"
Switch case Compiler error
use of Wrappers in switch() and case x: statements