aspose file tools*
The moose likes Beginning Java and the fly likes Switch Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Switch Statement" Watch "Switch Statement" New topic
Author

Switch Statement

Philip Pomario
Ranch Hand

Joined: Oct 03, 2003
Posts: 113
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

Joined: Oct 03, 2003
Posts: 113
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

Joined: Oct 12, 2000
Posts: 5093
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.


42
Philip Pomario
Ranch Hand

Joined: Oct 03, 2003
Posts: 113
Thanks Jeroen!
Philip Pomario
Ranch Hand

Joined: Oct 03, 2003
Posts: 113
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

Joined: Aug 07, 2003
Posts: 1646
Congratulations Filipe!

Here, have a beer ... you earned it.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Switch Statement