-1

I've been trying to self study on some java code. I came across the famous fizz buzz problem. I have a problem that on the last if statement the output is ok if its not enclosed in curly braces. what the difference of enclosing a statement inside a curly brace vs not? Edit: Output with curly brace (fizz, buzz, fizz, buzz, fizz , buzz ...) Output without curly brace*correct answer (1, 2, fizz, 4, buzz, fizz ...)

    boolean checker = true;
    for (int i  = 0; i < 100; i++){

        if (i % 3 == 0){
            System.out.print("Fizz");
            checker = false;
        }

        if (i % 5 == 0){
            System.out.print("Buzz");
            checker = false;
        }

        if (checker) { // here is the code if curly brace is removed the output is fine
            System.out.print(i);
            checker = true;
            System.out.print(",");
        }
    }
}
Onedaynerd
  • 49
  • 2
  • 9

3 Answers3

3

When you use if, else or for you dont need to have there {} but it will evaluate only first line after if, else or for.

if(condition)
//this line is affected by if block
//this is not

if(condition){
//all line in affected by if block
}
Milkmaid
  • 1,659
  • 4
  • 26
  • 39
1

Reason it works for you is, say you get i as 3 which is divisible by 3, then that means you will set checker variable as false and you will never enter the if(checker) condition block.

With braces, you define the block or boundary for if condition. So if you want to execute multiple statement within an if condition, you could use braces. By default if you don't provide brace then only the immediate next statement after if is going to get executed.

Note: I would suggest you to make use of braces even if you have single statement to execute within if.

SMA
  • 36,381
  • 8
  • 49
  • 73
0

Without brackets it wil execute the first statement for that condition. After it it stops using the condition.

Markvds
  • 137
  • 10