Java boolean
Created By: chatGPT
In Java, the
boolean
data type is a primitive data type that can hold one of two values: true or false. It is commonly used for conditional statements and logical operations.boolean isJavaFun = true;
boolean isFishTasty = false;
You can perform various logical operations using boolean values. The operators include AND (
&&
), OR (||
), and NOT (!
). These operators help combine or invert boolean values.boolean a = true;
boolean b = false;
boolean result1 = a && b; // result1 will be false
boolean result2 = a || b; // result2 will be true
boolean result3 = !a; // result3 will be false;
You can also use boolean values in if statements to control the flow of the program based on certain conditions.
boolean isWeekend = true;
if (isWeekend) {
System.out.println("It's the weekend!");
} else {
System.out.println("It's a weekday.");
}
In addition to simple conditions, you can also combine conditions using logical operators.
boolean hasLicense = true;
boolean isAdult = false;
if (hasLicense && isAdult) {
System.out.println("You can drive.");
} else {
System.out.println("You cannot drive.");
}
To declare a method that returns a boolean, you can specify the return type as
boolean
. Here's an example of a method that checks if a number is even.public boolean isEven(int number) {
return number % 2 == 0;
}
You can call this method and utilize its boolean return value in your program.
int num = 4;
if (isEven(num)) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}