File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hi can anybody explain 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 "Hi can anybody explain" Watch "Hi can anybody explain" New topic
Author

Hi can anybody explain

maha devan
Ranch Hand

Joined: Mar 16, 2004
Posts: 50
class JMM122 {
public static void main (String[] args) {
for (int i = 0; i < 4; i++) {
switch (i) {
case 0: System.out.print("A");
case 1: System.out.print("B");
case 2: System.out.print("C");
}}}}

What is the result of attempting to compile and run the program?

a. Prints: ABC
b. Prints: ABCC
c. Prints: CBA
d. Prints: ABCBCC
e. Run-time error
f. Compile-time error
g. None of the above


The answer given for this is ABCBCC How is that?
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Notice the lack of "break" statements in the switch block. Without a break statement, execution simply flows from one case into the next. Therefore, when i is 0, we print ABC, when i is 1, we print BC, and when i is 2, we print C. Of course, we have no cases that match 3 so nothing is printed in that case.

If you rewrite the code like this:



You'll get the output "ABC" from this.


SCJP Tipline, etc.
maha devan
Ranch Hand

Joined: Mar 16, 2004
Posts: 50
Ya Thanks Corey
 
 
subject: Hi can anybody explain