aspose file tools*
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
Author

For Switch char

joao ferreira
Greenhorn

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

//C
//E
//F


I don't understand why
C,E,F
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
Greenhorn

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 -
C
E
F

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

Joined: Jul 19, 2004
Posts: 5398
    
  13

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
http://www.javaroe.be/
joao ferreira
Greenhorn

Joined: Feb 23, 2009
Posts: 8
thanks a lot Now I understand
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: For Switch char