Introduction
In Java, booleans are a fundamental data type used to represent one of two values: true
or false
. Booleans are widely used in programming for decision-making and controlling the flow of execution through conditional statements like if
, while
, and for
.
Declaring a Boolean
boolean isJavaFun = true;
boolean isColdToday = false;
System.out.println("Is Java fun? " + isJavaFun); // Outputs: true
Relational Operators
Relational operators are used to compare two values. They evaluate the relationship between operands and return a boolean value (true
or false
).
Operator | Description | Example |
---|---|---|
== |
Equal to | a == b |
!= |
Not equal to | a != b |
> |
Greater than | a > b |
< |
Less than | a < b |
>= |
Greater than or equal to | a >= b |
<= |
Less than or equal to | a <= b |
Example of Relational Operators
int a = 10;
int b = 20;
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a > b); // false
System.out.println(a < b); // true
System.out.println(a >= 10); // true
System.out.println(b <= 20); // true
Logical Operators
Logical operators are used to combine multiple boolean expressions. They return a boolean result based on the logic.
Operator | Description | Example |
---|---|---|
&& |
Logical AND: true if both are true | a && b |
|| |
Logical OR: true if at least one is true | a || b |
! |
Logical NOT: inverts the boolean value | !a |
Example of Logical Operators
boolean isAdult = true;
boolean hasLicense = false;
// AND operator
System.out.println(isAdult && hasLicense); // false
// OR operator
System.out.println(isAdult || hasLicense); // true
// NOT operator
System.out.println(!isAdult); // false