Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Switch Statement

 
Philip Pomario
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy... I expected the following switch statement to match "default" (since it's in the first line) and fall through.

int k = 10;
switch(k){
default:
System.out.println("default");
break;
case 10:
System.out.println("ten");
case 20:
System.out.println("twenty");
break;
}

Though, the output is "ten", "twenty"... not "default"!

Where am I getting the switch() statement wrong?
 
Philip Pomario
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shouldn't it match values linearly? Thus, finding the "default" right in the beginning it would make this a successful match. I know I'm wrong, just can't see why.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're indeed wrong in your perception as to how a switch statement works.

First it tries to find a match.
If it does, it executes code from there on down to the first break.
If no match is found, it will execute code from the default statement on down to the first break.
 
Philip Pomario
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jeroen!
 
Philip Pomario
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just passed the SCJP1.4 exam and wanted to post this appreciation note to thank everyone who helped me understand Java a little better. Without your help this personal achievement wouldn't be possible.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Congratulations Filipe!

Here, have a beer ... you earned it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic