File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Urgent-switch case

 
Vrunda Joshi
Ranch Hand
Posts: 104
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • 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 ]
 
Anna Dow
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • 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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic