Sling Academy
Home/Kotlin/Kotlin - Working with Logical Operators: AND, OR, and NOT

Kotlin - Working with Logical Operators: AND, OR, and NOT

Last updated: December 05, 2024

Kotlin is a modern, statically typed programming language that runs on the Java Virtual Machine (JVM). It is widely used for developing Android applications, and among its many features is the capability to use logical operators to build complex logical expressions. In this article, we will explore how to use logical operators in Kotlin, specifically focusing on the AND (&&), OR (||), and NOT (!) operators.

Logical Operators in Kotlin

Logical operators in Kotlin allow you to combine boolean expressions to form more complex conditionals. These operators are essential in control flow statements such as if and while loops, enabling your program to react dynamically to different conditions.

AND (&&) Operator

The AND operator combines two boolean expressions and returns true if and only if both expressions evaluate to true. Otherwise, it returns false. Here's the syntax:


val expression = (a > b) && (c < d)
if (expression) {
    println("Both conditions are met.")
} else {
    println("One or both conditions are not met.")
}

In this snippet, the expression evaluates as true only if a is greater than b and c is less than d.

OR (||) Operator

The OR operator also combines two boolean expressions but returns true if at least one of them evaluates to true. It returns false only if both expressions are false. Here's how it looks in Kotlin:


val expression = (a < b) || (c > d)
if (expression) {
    println("At least one of the conditions is met.")
} else {
    println("Neither condition is met.")
}

With the OR operator, the expression will be true if either a is less than b or c is greater than d or both conditions are true.

NOT (!) Operator

The NOT operator is a unary operator that inverts the value of a boolean expression. If the expression is true, the NOT operator will return false, and vice versa. Here's an example:


val isValid = false
if (!isValid) {
    println("The value is not valid.")
} else {
    println("The value is valid.")
}

In this code, the not operator is applied to the isValid variable, making the expression true since isValid is initially false.

Combining Logical Operators

You can combine multiple logical operators to create intricate conditional expressions. This is handy in situations where multiple conditions need to be evaluated together. For example:


val a = 10
val b = 20
val c = 30

val complexExpression = (a < b) && (b < c) || !(c > a)

if (complexExpression) {
    println("The complex condition is satisfied.")
} else {
    println("The complex condition is not satisfied.")
}

In this snippet, pay attention to the order in which the logical operations are performed. Parentheses can be used to group expressions and dictate the order of evaluation.

Precedence and Short-circuiting

Logical operators have precedence rules that determine the order in which they are evaluated. In Kotlin:

  • The NOT operator (!) has a higher precedence than AND (&&) and OR (||).
  • The AND operator (&&) has a higher precedence than the OR operator (||).

Moreover, Kotlin supports short-circuit evaluation for these operators. This means evaluation stops as soon as the outcome is determined. For instance:


fun main() {
    val x = 1
    val y = 0

    if (y != 0 && x / y > 0) {
        println("Expression is true")
    } else {
        println("Expression is false")
    }
}

In this function, the AND operator stops evaluating once it finds y != 0 to be false, preventing a division by zero error.

In conclusion, effective utilization of logical operators is crucial for Kotlin programmers to streamline their coding processes, handle variable conditions proficiently, and build more readable and efficient code. Mastering these operators lays a strong foundation for advanced programming tasks.

Next Article: Understanding Conditional Expressions in Kotlin

Previous Article: How to Use `true` and `false` in Kotlin

Series: Primitive data types in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin