This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A switch-case statement question

 
Amelia Ma
Ranch Hand
Posts: 33
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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
  • 0
  • 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: 20834
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • 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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic