• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A switch-case statement question

 
Amelia Ma
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will be the result of attempting to compile and run the following program?

Correct answer is that the code will fail to compile. Because the value of the case label iFour is not a constant expression.
I totally don't understand. Isn't iFour is a compile time constant and become 4 through unboxing?
This problem come from "A Programmer's Guide to Java SCJP Certification", Chapter 6.2, page 215.
Thanks.
 
rohan yadav
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this:


Wrapping takes place at runtime(Integer to int), and you require compile time constants for switch case.
 
Rein de Boer
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to the previous post, iFour is a reference variable (to object type Integer), not a value type. So therefore not usable in a case.
 
Amelia Ma
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rein de Boer wrote:To add to the previous post, iFour is a reference variable (to object type Integer), not a value type. So therefore not usable in a case.


so all wrapper classes (Integer Character Short Byte) can't be in the case expression, right?
 
Henry Wong
author
Marshal
Pie
Posts: 21226
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Amelia Ma wrote:I totally don't understand. Isn't iFour is a compile time constant and become 4 through unboxing?


As a side note to this topic... compile time constants require that the type be a primative or a string. The Java Language Specification currently doesn't support any other type as a compile time constant.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic