Booleans in Kotlin
📌 Booleans in Kotlin
In Kotlin, a Boolean is a data type that represents one of two values:
truefalse
The Boolean type is often used for conditional logic, comparisons, and decision-making in programs.
✅ Declaring Boolean Variables
You can declare a Boolean variable using val (immutable) or var (mutable):
var isJavaEasy: Boolean = falseprintln(isKotlinFun) // Output: trueprintln(isJavaEasy) // Output: false
Kotlin also supports type inference, so you don't always need to specify Boolean explicitly:
val isSunny = true // Type inferred as Booleanvar isRainy = false // Type inferred as Boolean
✅ Boolean Operations
You can perform logical operations using the following operators:
| Operator | Description | Example | Result |
|---|---|---|---|
&& | Logical AND | true && false | false |
| ` | ` | Logical OR | |
! | Logical NOT (Negation) | !true | false |
📌 Example
val a = trueval b = falseprintln(a && b) // false (Both must be true)println(a || b) // true (At least one is true)println(!a) // false (Negates the value of 'a')
✅ Boolean with Conditional Statements
📍 Using If-Else
val isLoggedIn = trueif (isLoggedIn) { println("Welcome User!")} else { println("Please log in.")}
✅ Boolean with Comparison Operators
Kotlin provides standard comparison operators that return a Boolean result:
>(Greater than)<(Less than)>=(Greater than or equal to)<=(Less than or equal to)==(Equal to)!=(Not equal to)
📌 Example
val num1 = 10val num2 = 20println(num1 > num2) // falseprintln(num1 < num2) // trueprintln(num1 == num2) // falseprintln(num1 != num2) // true
✅ Boolean with Functions
You can return and manipulate Boolean values in functions:
fun (age: Int): Boolean { return age >= 18}println(isAdult(20)) // trueprintln(isAdult(16)) // false
✅ Conclusion
Booleans are simple and efficient for logical operations.
They are often used in decision-making using
if-elseandwhenstatements.Logical operators like
&&,||, and!are useful for complex conditions.Boolean values are returned from comparison operations.