Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Default value in switch construct

 
Nisheeth Kaushal
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Junilu Lacar
Bartender
Pie
Posts: 7465
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic