The boolean
keyword in Java is one of the eight primitive data types. It represents a logical value that can be either true
or false
. It’s fundamental to decision-making and control flow in Java programs. Think of it as the on/off switch of logic.
Declaring boolean
Variables:
You declare a boolean
variable using the boolean
keyword followed by the variable name:
boolean isLoggedIn;
boolean isRunning;
boolean hasCompleted;
Assigning Values:
You can assign either true
or false
to a boolean
variable:
isLoggedIn = true;
isRunning = false;
hasCompleted = true;
Using boolean
in Expressions:
boolean
values are primarily used in logical expressions and conditional statements. They are the result of comparisons and logical operations.
- Comparison Operators: Comparison operators (e.g.,
==
,!=
,>
,<
,>=
,<=
) produceboolean
results:
int age = 25;
boolean isAdult = age >= 18; // isAdult will be true
- Logical Operators: Logical operators (e.g.,
&&
(AND),||
(OR),!
(NOT)) combine or modifyboolean
values:
boolean hasPermission = isLoggedIn && isRunning; // true only if both are true
boolean isWeekend = day == "Saturday" || day == "Sunday"; // true if either is true
boolean isNotLoggedIn = !isLoggedIn; // true if isLoggedIn is false
Using boolean
in Control Flow:
boolean
values are essential for controlling the flow of execution in your programs. They are used in:
if
statements:
if (isLoggedIn) {
// Code to execute if isLoggedIn is true
System.out.println("Welcome!");
} else {
// Code to execute if isLoggedIn is false
System.out.println("Please log in.");
}
while
loops:
while (isRunning) {
// Code to execute as long as isRunning is true
// ... potentially change isRunning to false at some point
}
for
loops (in the conditional part):
for (int i = 0; i < 10 && !hasCompleted; i++) {
// Code to execute
}
- Ternary Operator:
String message = isLoggedIn ? "Welcome!" : "Please log in.";
Example:
public class LoginExample {
public static void main(String[] args) {
String username = "myuser";
String password = "mypassword";
boolean isLoggedIn = checkCredentials(username, password);
if (isLoggedIn) {
System.out.println("Login successful!");
} else {
System.out.println("Invalid username or password.");
}
}
static boolean checkCredentials(String username, String password) {
// In a real application, you would check against a database or other secure storage.
// This is a simplified example.
return username.equals("myuser") && password.equals("mypassword");
}
}
Key Points about boolean
:
boolean
variables can only hold two values:true
orfalse
.- They are the result of comparisons and logical operations.
- They are crucial for controlling program flow.
- They are a primitive data type in Java.
Let’s explore more examples of the boolean
keyword in Java, focusing on different usage scenarios and demonstrating its versatility.
1. Checking Range:
public class RangeCheck {
public static void main(String[] args) {
int temperature = 25;
boolean isComfortable = temperature >= 20 && temperature <= 30;
if (isComfortable) {
System.out.println("The temperature is comfortable.");
} else {
System.out.println("The temperature is not comfortable.");
}
}
}
This example checks if the temperature
is within a specific range (20 to 30 degrees). The &&
(AND) operator ensures that both conditions must be true for isComfortable
to be true.
2. Even or Odd:
public class EvenOdd {
public static void main(String[] args) {
int number = 17;
boolean isEven = number % 2 == 0; // Remainder 0 means even
if (isEven) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}
}
}
Here, we use the modulo operator (%
) to check if a number is even or odd. If the remainder after dividing by 2 is 0, the number is even.
3. Checking for Null or Empty String:
public class StringCheck {
public static void main(String[] args) {
String text = ""; // Or null
boolean isEmpty = text == null || text.isEmpty();
if (isEmpty) {
System.out.println("The string is either null or empty.");
} else {
System.out.println("The string is: " + text);
}
}
}
This example demonstrates how to check if a string is either null
or empty. The ||
(OR) operator checks if either condition is true. This is a common pattern when handling user input or data from external sources.
4. Combining Conditions:
public class ComplexCondition {
public static void main(String[] args) {
int age = 20;
boolean hasLicense = true;
boolean hasInsurance = false;
boolean canDrive = age >= 18 && hasLicense && hasInsurance;
if (canDrive) {
System.out.println("This person can drive.");
} else {
System.out.println("This person cannot drive.");
}
}
}
This example combines multiple conditions using &&
(AND). The person can only drive if they are at least 18 years old, have a license, and have insurance.
5. Using boolean
Flags:
public class Game {
boolean gameOver = false;
int score = 0;
public void play() {
while (!gameOver) { // Game continues as long as gameOver is false
// ... game logic ...
score++;
if (score > 100) {
gameOver = true; // Game ends when score reaches 100
}
}
System.out.println("Game Over! Final score: " + score);
}
public static void main(String[] args) {
Game myGame = new Game();
myGame.play();
}
}
Here, gameOver
acts as a flag to control the game loop. The game continues as long as gameOver
is false
. This is a common way to manage the state of a program or loop.
6. Returning boolean
from a Method:
public class Validation {
public static boolean isValidEmail(String email) {
// ... complex email validation logic ...
return email.contains("@") && email.contains("."); // Simplified check
}
public static void main(String[] args) {
String email = "test@example.com";
boolean isValid = isValidEmail(email);
if (isValid) {
System.out.println("The email is valid.");
} else {
System.out.println("The email is invalid.");
}
}
}
This example shows a method isValidEmail
that returns a boolean
value. This is a common practice for validation or checking conditions.