Skip to content

[Edit] Java: Boolean Logic #7102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
d0dd9bd
[Edit] SQL: DATEDIFF()
mamtawardhani May 21, 2025
9f5c19b
Update datediff.md
mamtawardhani May 21, 2025
c32e9f3
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
4170ba2
Merge branch 'Codecademy:main' into main
mamtawardhani May 23, 2025
8325585
Merge branch 'Codecademy:main' into main
mamtawardhani May 26, 2025
8f6f8e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 27, 2025
e4c54e8
Merge branch 'Codecademy:main' into main
mamtawardhani May 28, 2025
7b3b9c0
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
27ecefd
Merge branch 'Codecademy:main' into main
mamtawardhani May 29, 2025
0392da4
Merge branch 'Codecademy:main' into main
mamtawardhani May 30, 2025
d550fa7
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 2, 2025
793be7d
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
2f03b61
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
25eb0ab
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 3, 2025
73e0e3b
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 4, 2025
44f4c63
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 5, 2025
545a8da
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 6, 2025
49d85cd
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 9, 2025
f488437
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 10, 2025
9b642e6
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 11, 2025
afb1cf5
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 12, 2025
dc740fb
Merge branch 'Codecademy:main' into main
mamtawardhani Jun 13, 2025
1ad9a26
[Edit] Java: Boolean Logic
mamtawardhani Jun 13, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
245 changes: 204 additions & 41 deletions content/java/concepts/boolean-logic/boolean-logic.md
Original file line number Diff line number Diff line change
@@ -1,73 +1,236 @@
---
Title: 'Boolean Logic'
Description: 'A set of operators and methods in Java for manipulating booleans.'
Description: 'A set of operators and expressions in Java used to evaluate and manipulate boolean values (true or false).'
Subjects:
- 'Computer Science'
- 'Code Foundations'
- 'Web Development'
Tags:
- 'Booleans'
- 'Logic'
- 'Logical'
- 'Operators'
- 'Conditionals'
- 'Java'
- 'Data Types'
- 'Variables'
CatalogContent:
- 'learn-java'
- 'paths/introduction-to-android-with-java'
- 'paths/computer-science'
---

One of the primitive [data types](https://www.codecademy.com/resources/docs/java/data-types) in Java is the `boolean`. A boolean object takes a value of `true` or `false`.
The **boolean** data type is one of the eight primitive data types in Java and is used to represent logical values. A boolean variable can hold only two possible values: `true` or `false`. It is commonly used to represent binary states such as on/off, yes/no, or enabled/disabled.

**Boolean logic** describes how boolean values can be combined and manipulated. Java implements boolean logic through a set of [operators](https://www.codecademy.com/resources/docs/java/operators) and [methods](https://www.codecademy.com/resources/docs/java/methods).
Building on this, **boolean logic** in Java refers to the use of boolean values in combination with logical operators like `&&` (AND), `||` (OR), and `!` (NOT) to evaluate conditions and control program behavior. This logic forms the backbone of decision-making in programming—guiding how a program responds to different inputs or situations. Boolean logic is widely used in conditional statements, loops, and validations, with practical applications such as form validation, user authentication, feature toggles, and game state control.

## Boolean Logical Operators
## Syntax

The boolean logical operators available in Java are described in the following table:
```pseudo
boolean variableName = value;
```

**Parameters:**

- `variableName`: The name of the boolean variable following Java naming conventions
- `value`: Either `true` or `false` (case-sensitive)

**Return value:**

A boolean data type does not return a value but stores a logical state that can be evaluated in expressions.

### Boolean Logical Operators

Boolean values can be combined and manipulated using logical operators:

- `&&` (AND): Returns `true` if both operands are `true`
- `||` (OR): Returns `true` if at least one operand is `true`
- `!` (NOT): Returns the opposite boolean value
- `^` (XOR): Returns `true` if operands have different values

### Boolean Logical Methods

The Boolean wrapper class provides several useful methods for working with boolean values:

- `Boolean.parseBoolean(String s)`: Converts a string to a boolean value
- `Boolean.toString(boolean b)`: Converts a boolean to its string representation
- `Boolean.valueOf(boolean b)`: Returns a Boolean object representing the specified boolean value
- `Boolean.compare(boolean x, boolean y)`: Compares two boolean values

## Example 1: Basic Boolean Declaration

This example demonstrates the fundamental way to declare and use boolean variables in Java:

```java
public class BooleanBasics {
public static void main(String[] args) {
// Declare boolean variables with initial values
boolean isJavaFun = true;
boolean isTestPassed = false;

// Display the values
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Did the test pass? " + isTestPassed);

// Boolean values from expressions
boolean isPositive = (10 > 0);
boolean isEqual = (5 == 3);

System.out.println("Is 10 positive? " + isPositive);
System.out.println("Is 5 equal to 3? " + isEqual);
}
}
```

The output of this code is:

```shell
Is Java fun? true
Did the test pass? false
Is 10 positive? true
Is 5 equal to 3? false
```

This example shows how boolean variables can be declared with literal values (`true`/`false`) or assigned the result of boolean expressions. The comparison operators automatically return boolean values.

## Example 2: User Login Validation

This example demonstrates a real-world scenario where booleans are used to validate user credentials and control access to system features.

```java
import java.util.Scanner;

| Operator Symbol | Syntax | Behavior | Equivalent Logical Concept |
| --------------- | ------------------------------ | -------------------------------------------------------------------------------- | --------------------------- |
| `&&` | `(boolean A) && (boolean B)` | Returns `true` if both arguments equal `true`; otherwise returns `false` | AND / Conjunction |
| `\|\|` | `(boolean A) \|\| (boolean B)` | Returns `true` if at least one argument equals `true`; otherwise returns `false` | OR / Inclusive disjunction |
| `!` | `!(boolean A)` | Returns `true` if the argument equals `false`; otherwise returns `false` | NOT / Negation |
| `^` | `(boolean A) ^ (boolean B)` | Returns `true` if exactly one argument equals `true`; otherwise returns `false` | XOR / Exclusive disjunction |
public class UserLoginSystem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

## Boolean Logical Methods
// Predefined user credentials
String validUsername = "admin";
String validPassword = "password123";

The boolean logical methods available in Java are described in the following table:
System.out.print("Enter username: ");
String inputUsername = scanner.nextLine();

| Method Syntax | Behavior | Equivalent Logical Concept |
| ---------------------------------- | ---------------------------------- | --------------------------- |
| `logicalAnd(boolean A, boolean B)` | Returns the result of `(A && B)` | AND / Conjunction |
| `logicalOr(boolean A, boolean B)` | Returns the result of `(A \|\| B)` | OR / Inclusive disjunction |
| `logicalXor(boolean A, boolean B)` | Returns the result of `(A ^ B)` | XOR / Exclusive disjunction |
System.out.print("Enter password: ");
String inputPassword = scanner.nextLine();

### Use in Conditionals
// Boolean validation
boolean isUsernameValid = inputUsername.equals(validUsername);
boolean isPasswordValid = inputPassword.equals(validPassword);
boolean isLoginSuccessful = isUsernameValid && isPasswordValid;

Boolean logic is commonly used within conditionals to control the flow of a program.
// Display results
System.out.println("Username valid: " + isUsernameValid);
System.out.println("Password valid: " + isPasswordValid);

## Example
if (isLoginSuccessful) {
System.out.println("Login successful! Welcome to the system.");
} else {
System.out.println("Login failed. Please check your credentials.");
}

scanner.close();
}
}
```

The output (with correct credentials) is as follows:

The following example illustrates the use of boolean logical operators within conditionals.
```shell
Enter username: admin
Enter password: password123
Username valid: true
Password valid: true
Login successful! Welcome to the system.
```

This example illustrates how booleans are used in authentication systems to validate user input and control access. The logical AND operator (`&&`) ensures both conditions must be true for successful login.

## Example 3: Shopping Cart Discount Calculator

This example shows how booleans can be used in e-commerce applications to determine eligibility for discounts and special offers:

```java
// File: GateTest.java
public class GateTest{
public static void main(String args[]) {
boolean gate1IsOpen = false ;
boolean gate2IsOpen = false ;
boolean gate3IsOpen = true ;
if(!(gate1IsOpen || gate2IsOpen || gate3IsOpen)){
System.out.println("All gates closed.");
public class ShoppingCartDiscount {
public static void main(String[] args) {
// Customer information
double totalAmount = 120.50;
boolean isPremiumMember = true;
boolean hasPromoCode = false;
int itemCount = 5;

// Discount eligibility conditions
boolean qualifiesForBulkDiscount = itemCount >= 5;
boolean qualifiesForMemberDiscount = isPremiumMember;
boolean qualifiesForPromoDiscount = hasPromoCode;
boolean qualifiesForMinimumPurchase = totalAmount >= 100.0;

// Determine applicable discounts
boolean canApplyBulkDiscount = qualifiesForBulkDiscount && qualifiesForMinimumPurchase;
boolean canApplyMemberDiscount = qualifiesForMemberDiscount;
boolean canApplyPromoDiscount = qualifiesForPromoDiscount;

// Calculate final discount
double discountPercentage = 0.0;

if (canApplyBulkDiscount) {
discountPercentage += 10.0; // 10% bulk discount
}
else {
System.out.println("Gate open! Identify and close immediately.");

if (canApplyMemberDiscount) {
discountPercentage += 5.0; // 5% member discount
}

if (canApplyPromoDiscount) {
discountPercentage += 15.0; // 15% promo discount
}

double discountAmount = totalAmount * (discountPercentage / 100);
double finalAmount = totalAmount - discountAmount;

// Display results
System.out.println("=== Shopping Cart Summary ===");
System.out.println("Original Amount: $" + totalAmount);
System.out.println("Premium Member: " + isPremiumMember);
System.out.println("Has Promo Code: " + hasPromoCode);
System.out.println("Item Count: " + itemCount);
System.out.println();
System.out.println("Discount Eligibility:");
System.out.println("Bulk Discount (5+ items, $100+ purchase): " + canApplyBulkDiscount);
System.out.println("Member Discount: " + canApplyMemberDiscount);
System.out.println("Promo Discount: " + canApplyPromoDiscount);
System.out.println();
System.out.println("Total Discount: " + discountPercentage + "%");
System.out.println("Discount Amount: $" + String.format("%.2f", discountAmount));
System.out.println("Final Amount: $" + String.format("%.2f", finalAmount));
}
}
```

The above example gives following output:
The output of this code is:

```shell
Gate open! Identify and close immediately.
=== Shopping Cart Summary ===
Original Amount: $120.5
Premium Member: true
Has Promo Code: false
Item Count: 5

Discount Eligibility:
Bulk Discount (5+ items, $100+ purchase): true
Member Discount: true
Promo Discount: false

Total Discount: 15.0%
Discount Amount: $18.08
Final Amount: $102.42
```

This example demonstrates how booleans are used in business logic to evaluate multiple conditions and determine eligibility for various discounts. The boolean variables make the code readable and maintainable while handling complex business rules.

## Frequently Asked Questions

### 1. Can boolean variables be assigned integer values like 1 or 0?

No, unlike some programming languages, Java boolean variables can only be assigned `true` or `false` values. Attempting to assign integer values like 1 or 0 will result in a compilation error. Java maintains strict type safety for boolean values.

### 2. What is the default value of a boolean variable?

For instance variables and static variables, the default value is `false`. However, local variables must be explicitly initialized before use, as they do not have default values.

### 3. Can boolean values be used in arithmetic operations?

No, boolean values cannot be directly used in arithmetic operations like addition or multiplication. Java does not perform automatic conversion between boolean and numeric types. To perform calculations with boolean values, you must first convert them explicitly.