Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hi can anybody explain

 
maha devan
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
maha devan
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya Thanks Corey
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic