Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why and how output is 8 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 "why and how output is 8" Watch "why and how output is 8" New topic
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why and how output is 8
 
Similar Threads
Puzzled with the output of this programme
array question
Reg. class initialization sequence
Need explanation about three dimensional arrays
j++ IN switch()