#boolean conditions in java

1 messages · Page 1 of 1 (latest)

modern forum
#

Hello guys, sorry to disturb you, I just have a quick question concerning boolean conditions.

Consider these lines of codes:

public class BooleanConditionForLoop {
    public static void main(String[] args) {
        int counter = 0;

        // Initialize a boolean variable in the for loop
        for (boolean keepLooping = true; keepLooping; counter++) {
            System.out.println("Counter is: " + counter);
            
            // Condition to stop the loop when counter reaches 5
            if (counter >= 5) {
                keepLooping = false;
            }
        }

        System.out.println("Loop has ended.");
    }
}
  1. Whenever we initialize a boolean variable, we should always initialize it to true?

2.If ever we write this:

boolean checking = false;

if (checking) {
. . .
} // This if statement how do we read it, do we read it as follows: If checking is true then do.... or if checking if false then do .... , like does the assignment checking = false has an impact on the condition please

  1. Also notice that in the for loop, we write, we initialize a boolean variable in the parentheses for (boolean...) didn't know that it was possible... I always used int values.... we can actually initialize any value we want ?
tidal blazeBOT
#

<@&987246399047479336> please have a look, thanks.

severe falcon
#
  1. depends on the usecase
  2. you will not enter the if, since the value is false
  3. yes
  4. why not do for(int i = 0; i < 5; i++){
modern forum
#

hmm why won't we enter the if if the value if false please

#

yeah I could have written for (int i = 0....) it was just to test if we can use other data types in there

#

oh okay so we always read it as this : if true, even though checking = false, we don't read it like that: if false

severe falcon
#

Indeed.

#

If (conditionEvaluatesToTrue) => do something.

#

Given your example used checking=false.

modern forum