• Post Reply Bookmark Topic Watch Topic
  • New Topic

Puzzling over switch behavior  RSS feed

 
Stephen-Austin Murphy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Silly question, but I need to ask it.

Given the following code:

The output of this is:
120
121
127

Of course what happens is that control hits the test for 120 and prints 120. Because there is no "break" associated with that case, then flow continues with the 121 and 127 tests, exiting with the break in the 127 case.
But it is counter-intuitive that the println's associated with 121 and 127 would actually execute. It seems more logical that the makers of Java would have decided that statements associated with non-matches would not execute. So in other words, in this example, 120 does not match 121 so it is more logical that the println("121") should not execute.

So I'm wondering why the makers of Java would allow a switch statement to behave this way. Does anyone have any thoughts?

I hope that made sense. (Ravings of a mad man )

Kind regards,
Steve




 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13078
6
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually I have found that "fall through" operation to be quite convenient from time to time so I like the requirement for break. Sometimes "return" is quite convenient also.

Bill
 
Raymond Tong
Ranch Hand
Posts: 255
2
IntelliJ IDE Java Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It may be useful for multiple matches
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephen-Austin Murphy wrote:But it is counter-intuitive that the println's associated with 121 and 127 would actually execute. It seems more logical that the makers of Java would have decided that statements associated with non-matches would not execute...So I'm wondering why the makers of Java would allow a switch statement to behave this way. Does anyone have any thoughts?

It goes back to the origins of Java, which was based on C/C++, and the syntax of the switch statement in Java is almost identical to that of C (except that Duff's device is not allowed).

I agree that it's not the best, and to this day I still sometimes forget to put in the break; but as William says, there are times when the "fallthrough" is quite useful.

Winston
 
Stephen-Austin Murphy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Winston and Raymond. It makes more sense now.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!