🔹 Definition:
A flag is a boolean variable (either true or false) used to indicate a condition or state in a program. It helps in making decisions using if conditions or loops.
🔹 Why Use a Flag?
To check if something happened or not (like found/not found, valid/invalid, etc.)
Ex
public class FlagExample {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 7, 8};
boolean foundOdd = false; //
for (int num : numbers) {
if (num % 2 != 0) { // Check for odd number
foundOdd = true; // Set flag to true if odd found
break;
}
}
if (foundOdd) {
System.out.println("Odd number found!");
} else {
System.out.println("All numbers are even.");
}
}
}
https://www.quora.com/How-can-the-flag-be-used-in-a-Java-program
Top comments (0)