Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why and how output is 8

 
Venkat Ramsimha
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class SwitchTest
{
public static void main(String []args)
{
System.out.PrintIn("value =" +switchIt(4));
}
public static int switchIt(int x)
{
int j = 1;
switch(x)
{
case 1: j++;
case 2: j++;
case 3: j++;
case 4: j++;
case 5: j++;
default:j++;
}
return j + x;
}
}

hi all,
can anybody explain y for the above program the output is 8

thanks,
venkat
 
Kumar J
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Venkat Ramsimha:
public class SwitchTest
{
public static void main(String []args)
{
System.out.PrintIn("value =" +switchIt(4));
}
public static int switchIt(int x)
{
int j = 1;
switch(x)
{
case 1: j++;
case 2: j++;
case 3: j++;
case 4: j++;
case 5: j++;
default:j++;
}
return j + x;
}
}

hi all,
can anybody explain y for the above program the output is 8

thanks,
venkat


since x=4 -> execution starts from case 4
j=1 becomes j=2 then
j=2 becomes j=3 then at last in default
j=3 becomes j=4 then
then we have return j+x; which is return 4 + 4; so 8 is output

 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Mr Kumar J" (aka Mr Kumar V) please change your displayed name to conform to our JavaRanch Naming Policy. In short: No "Mr", and a displayed name in the format <first name> <family name>. You may use initials only in place of your first name. You can change your displayed name via the "My Profile" link.
Thanks
-Barry

(NR)
[ May 12, 2005: Message edited by: Barry Gaunt ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Venkat, the best way to do these problems is by using paper and pencil and to run the program in your head. Notice that there are no break statements in this code so that execution will "fall through" from one case to the next.
 
Venkat Ramsimha
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks kumar and barry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic