| Author |
final static Integer not considered a constant?
|
Annie Jones
Greenhorn
Joined: Nov 05, 2007
Posts: 10
|
|
Hi everyone, Could someone explain to me why the following declaration is not considered to be a constant? final static Integer x = 7; If I try to use this in a switch statement, as below, I get a compiler error stating that 'case expressions must be constant expressions'. I thought that because the Integer object is immutable it would be ok? Thanks for any help!
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 23247
|
|
|
I think it's because "x" has to be auto-unboxed to be an "int", that int isn't considered a compile-time constant.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18641
|
|
|
Yes. Case statements can only take compile-time constants, or enums, and the definition of compile-time constant expressions can only be applied to primitives and Strings. That's just the way they wrote the rules. On the one hand, yes the compiler has access to enough information here that it could probably figure out how to use an int rather than an Integer here. On the other hand, there's really no reason this number needs to be an Integer in the first place, is there? It can easily be changed to an int, and everything will work fine.
|
"I'm not back." - Bill Harding, Twister
|
 |
Annie Jones
Greenhorn
Joined: Nov 05, 2007
Posts: 10
|
|
Cool, thanks! Your reply makes a lot of sense
|
 |
 |
|
|
subject: final static Integer not considered a constant?
|
|
|