File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "flow controls" Watch "flow controls" New topic

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?
in the above syntax case4:s+="e" gives a compile 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

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: 15081

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 8 API documentation
I agree. Here's the link:
subject: flow controls
It's not a secret anymore!