File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problems understanding the "default case" in a switch statement

 
Kai Wähner
Ranch Hand
Posts: 76
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I thought that the default case matches every expression, isn't this correct?

But on the SCJP mock exam, a question occured something like this:



I know that it is not allowed to use two expressions with case 3 in a single switch statement, but I thought "default" will match the "3" expression (because it matches everything) and print "Invalid month.", but the solution says that case 3 "March" is correct?
Can you please explain this? Thank you.


Best regards,
Kai
 
Ankit Garg
Sheriff
Posts: 9495
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even though your default is in the middle of other case statements, this doesn't mean the case labels after the default will be ignored. Since the switch expression is 3, so the case labeled 3 will be a match and thus the default case won't be used...
 
Matthew Brown
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
default doesn't match everything, it matches anything not explicitly matched by a case expression. So in your case case 3 takes precedence.
 
ujjawal rohra
Ranch Hand
Posts: 105
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes default matches everything BUT ONLY when there is no exact match available.
In your example if there was no case 3: then default would have surely matched.

Hope this would help
 
Kai Wähner
Ranch Hand
Posts: 76
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your comments. Now it is clear.

I thought that each case is evaluated one after another, but all are evaluated at once (otherwise the default would not know that there will be another case that matches...)
 
ujjawal rohra
Ranch Hand
Posts: 105
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome dear
 
Sandra Bachan
Ranch Hand
Posts: 434
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The position of default is irrelevant, it can be in the beginning of the case statement
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic