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 Urgent-switch case 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 "Urgent-switch case" Watch "Urgent-switch case" New topic

Urgent-switch case

Vrunda Joshi
Ranch Hand

Joined: Dec 03, 2001
Posts: 104
i have just solved a mock exam.i am doubtful for a question.the question was
"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

Joined: Aug 26, 2001
Posts: 7610
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 ]

[Blog] [Blogroll] [My Reviews] My Linked In
Anna Dow

Joined: Jun 04, 2002
Posts: 18
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:
subject: Urgent-switch case
It's not a secret anymore!