• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Urgent-switch case

 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
i have just solved a mock exam.i am doubtful for a question.the question was
True/False
"In a swith statement,the argument to the case label(case:argument) can be any variable which can fit within an int."

As per my knowledge,the allowable value for the case label can be of integral type ie: char,short,byte & int.
so the ans for this question could be true.
but the ans given is false and the explanation given is
" The case argument must be either an int literal or an int compatible variable which is constant (ie: static final) "
Can anybody help me with the clarification of these question/ans.This is a bit Urgent
Thanks in advance.
-Vrunda Divekar
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From JLS 14.10 The switch Statement

The type of the Expression must be char, byte, short, or int, or a compile-time error occurs.

The problem here is that a long primitive like 12L fits perfectly within an int but a long is not allowable in a case expression.
If you try to compile the following code

it gives you the following error:

[ June 12, 2002: Message edited by: Valentin Crettaz ]
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You may use variables for case label, but only if they are constants (that is, final). For example, the code:

compiles fine. If you do not decalare j as final, compiler gives error 'constant expression required' for line 1
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic