aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Default value in switch construct Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Default value in switch construct" Watch "Default value in switch construct" New topic
Author

Default value in switch construct

Nisheeth Kaushal
Ranch Hand

Joined: Jul 20, 2001
Posts: 87
Hello friends,
I am using the rules round up game of this site and there i find a question that
"In a switch construct, the default value will execute if no values match the switch() construct.
I make it false b'coz i think that a default value may also execute if there is no break statement with the previous one."
But the forum says it true, "if there are no matching construct found the default will run."
please help,
Nisheeth
Mr Iftikhar
Ranch Hand

Joined: Oct 12, 2001
Posts: 39
int x=10;
switch(x){
case 1: System.out.println("one");
case 2: System.out.println("two");
case 3: System.out.println("three");
default: System.out.println("default");
}
the above code will work properly without break .
or if you will give the break in each case.
there is no effect on th ecode.


java language
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 5288
    
  10

The code Mr Iftikhar gave will seem to work the same with or without breaks in each case if x is not 1, 2, or 3! However, the program works differently if x is 1,2,or 3, depending on whether or not you have a break in each case. Just want to make that point clear.
[ February 09, 2002: Message edited by: Junilu Lacar ]

Junilu - [How to Ask Questions] [How to Answer Questions]
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12836
    
    5
"In a switch construct, the default value will execute if no values match the switch() construct.
I make it false b'coz i think that a default value may also execute if there is no break statement with the previous one."
But the forum says it true, "if there are no matching construct found the default will run."

There is nothing false about the statement just because default may execute under other conditions. Watch out for convoluted thinking like this on the real test.
Also don't assume that default will be the last case in a switch statement - there is no requirement for that, it is just common practice.
Bill
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Default value in switch construct