File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Associate Certification (OCAJP 7/8) and the fly likes For Switch char Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Associate Certification (OCAJP 7/8)
Bookmark "For Switch char" Watch "For Switch char" New topic

For Switch char

joao ferreira

Joined: Feb 23, 2009
Posts: 8
What letters will be printed by this program?


I don't understand why
Stuart A. Burkett
Ranch Hand

Joined: May 30, 2012
Posts: 679
What were you expecting and why ?
meghana chintanippu
Ranch Hand

Joined: Dec 20, 2013
Posts: 42
even i have the same doudt how is the case getting matched with i= 2 but not for i=0,1. can you please tell the conversion of int to char in this question
Sanju Nair

Joined: Jun 23, 2010
Posts: 6
In first iteration of for loop, value assigned to var i of type char is 'int' value 0. While executing the switch statement, value of i is still int 0(as the operator is port-incremental). Since '0' (char) and 0 (int) are not the same, control exists from the switch block as there is no matching case statement. And since, the switch statement contains the post-incremental operator, value of i is 1 now. At the end of the first iteration of for loop, i is again incremented by 1(update clause of for loop). Which means, in the second iteration value of i is 2(int) - hence printing "C". In third iteration, value of i is 4(int), hence printing "E" and since there is no break statement, it executes the next statement as well, hence printing "F" too.

Hence, you get the output -

Debugging the code will give you insight into how control flows.
Roel De Nijs

Joined: Jul 19, 2004
Posts: 8364

Sanju Nair wrote:Debugging the code will give you insight into how control flows.

Or you can add a few well-placed SOPs to print the value of the char variable, as shown in the next code snippet.

SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
joao ferreira

Joined: Feb 23, 2009
Posts: 8
thanks a lot Now I understand
I agree. Here's the link:
subject: For Switch char
It's not a secret anymore!