• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

flow controls

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ...
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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).
 
I promise I will be the best, most loyal friend ever! All for this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic