| Author |
why and how output is 8
|
Venkat Ramsimha
Ranch Hand
Joined: Dec 28, 2004
Posts: 127
|
|
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
Joined: Feb 13, 2005
Posts: 35
|
|
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
|
With Regards,<br />Kumar J
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
"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 ]
|
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
|
 |
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
|
|
|
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
Joined: Dec 28, 2004
Posts: 127
|
|
|
thanks kumar and barry
|
 |
 |
|
|
subject: why and how output is 8
|
|
|