Reputation: 197
So question about Java indents and if statements. I'm familiar with python where the info may not transfer 1 to 1.
So if I had a for loop with an if statement in it, and I close that if statement with a } but the next line has the same indention place as the if statement. What happens in the the new line, after the if statement is closed. For example.
for (int i = 0; i < 10; i++) {
if (i == 5) {
do something here;
}
what happens here, is this the else that's not written explicitly?
}
Upvotes: 0
Views: 98
Reputation: 23
for (int i = 0; i < 10; i++) {
if (i == 5) {
do something here;
}
//if you write something here, it will be executed after the if statement
}
If you would write that into else{} it would just be executed, if the if statement isn't true...
So the line after the if statement will be executed, even, when the if statement is true
Upvotes: 0
Reputation: 4185
The line you are referring to will be executed 10 times, regardless whether the if
statement is true or false, i.e., is executed or not.
Indention in Java is just a way to make code more readable.
So the output would be (replacing "do something here;" with System.out.println("i is 5")
and replacing "what happens here ..." with System.out.println("i is not 5")
(actual value of i
in square brackets, not part of the output):
i is not 5 [0]
i is not 5 [1]
i is not 5 [2]
i is not 5 [3]
i is not 5 [4]
i is 5 [5]
i is not 5 [5]
i is not 5 [6]
i is not 5 [7]
i is not 5 [8]
i is not 5 [9]
Upvotes: 4