• 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

A switch-case statement question

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 156
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try this:


Wrapping takes place at runtime(Integer to int), and you require compile time constants for switch case.
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic