• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper class variable in switch

 
Vijay Chandran
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Dear friends,

We can pass primitive values like int,char to switch statement. But this code passes an object of Integer (wrapper) variable to the switch statement. The compiler didn't complain anything about this. It executed perfectly.

Please explain me why this happened.

Thanks in advance.
Regards,
Vijay
 
Pho Tek
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
autoboxing
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JLS - 14.11 The switch Statement...
SwitchStatement:
switch ( Expression ) SwitchBlock

...

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, or an enum type...
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
boolean testIfFound(Integer i)
{
boolean found;
final int switchValue = i.intValue();
switch(i)
{
case 0: found = true;
case 1: found = true;
// ..... and so on
// ..... and so on
// ..... and so on
// ..... and so on
// ..... and so on
// ..... and so on
}

return found:
}
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nicholas Jordan:
boolean testIfFound(Integer i)
{
boolean found;
final int switchValue = i.intValue();
switch(i)
{
case 0: found = true;
case 1: found = true;
// ..... and so on
// ..... and so on
// ..... and so on
// ..... and so on
// ..... and so on
// ..... and so on
}

return found:
}

You forgot the break statements.
 
Vijay Chandran
Ranch Hand
Posts: 186
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for the reply.

Sorry for the delayed thanks!! Just now checked the forum.


Regards,
Vijay
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Rob Prime:]   You forgot the break statements.

Yes, I did - but the switch I wrote will cascade along the steppes and could have as well have been written:



Switch cases do not necessarily need the breaks, in this one the cascading down the chain just wastes a few dozen processor cycles ~ the effect is the same.
[ September 21, 2007: Message edited by: Nicholas Jordan ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic