0

Why here i'm getting not concatenated string

String zero = "0";
        for (int i = 0; i <= 5; i++)
            System.out.println(zero);
            zero += "0";

and here i'm able to concatenate?

String test = "Hello";
        System.out.println(test);
        test += "world!";
        System.out.println(test);

1 Answers1

1

When a for-loop has no curly braces then only the very next statement is repeated:

String zero = "0";
for (int i = 0; i <= 5; i++) {
  System.out.println(zero);
  zero += "0";
}

Note that indentation has no syntactic value in Java, so the fact that both the println and concatenation statements are indented in your example misleads the reader to think that both statements are repeated when only the println statement is.

maerics
  • 151,642
  • 46
  • 269
  • 291