0

There is this simple program which has loops and jump statement. I am unable to figure out the output that it is giving.

public class Breaker2{
static String o = "";
public static void main(String[] args) {
  z:
  for(int x = 2; x < 7; x++) {
     //System.out.println(o + "  x is this  : " + x);
     if(x==3) continue;
     if(x==5) break z;
     o = o + x;  //2nd question is about this piece of code
  }
  System.out.println(o);
  }
}

I am having the following doubts, Sorry if someone finds them simple or silly.

1. Why cannot I place a Print statement immediately after the jump label (z:)

  1. How is it able to convert from int to string and add/contact the x variable
  2. I see that the output 24 comes only by concatenating the values of x. Is it the right conclusion?

2 Answers2

0

a. Why cannot I place a Print statement immediately after the jump label (z:)

because label statements can't be labelled, only blocks {} can be labelled.

b. How is it able to convert from int to string and add/contact the x variable

its overloading operation of '+' which concatenates the objects/primitives when either of parameter is string, it concatenates both the side.

c. I see that the output 24 comes only by concatenating the values of x. Is it the right conclusion?

yes the result was of concatenation of o + x

Ankit
  • 6,554
  • 6
  • 49
  • 71
0

Why cannot I place a Print statement immediately after the jump label ? (z:)

When you define a label (like Z:), you should define a scope for it ({}), and The scope of a label of a labeled statement is the immediately contained Statement. See JLS 14.7

If you write something like this ( please note that i have purposefully removed x from sysout to avoid one more error)

        z:
        System.out.println(o + "  x is this  : ");
        for(int x = 2; x < 7; x++) {
            if(x==3) continue;
            if(x==5) break z;
            o = o + x;
        }

The scope of z: becomes only sysout statment, and not for loop. to make it work you can define scope with {} like this

      z: {
            System.out.println(o + "  x is this  : ");
            for(int x = 2; x < 7; x++) {
                if(x==3) continue;
                if(x==5) break z;
                o = o + x;
            }
        }
  • How is it able to convert from int to string and add/contact the x variable
  • I see that the output 24 comes only by concatenating the values of x. Is it the right conclusion?

o is a String and o + x is assigned back to o. So the output of + operation should be String. hence Java converts x into String (by doing x.toString()) and concatenates the content of o and x to produce 24

sanbhat
  • 17,522
  • 6
  • 48
  • 64