Kotlin Boolean Logical Operations & Usage Examples | Android Introduction #11

ibrahimcanerdogan
5 min readJan 17, 2024

--

In this reading, you will learn how to use logical Boolean operators.

UDEMY COURSE

Just like you can perform operations on numbers, you can also perform operations on Boolean values. For example, think about the phrase, “if I run 5 miles and lift weights, I will buy pizza tonight”. In order to buy pizza, both parts of the condition have to be met. The connection between the two conditions is called a logical operator.

Keep reading to learn how to construct these logical expressions in code.

The ‘and’ operator (&&)

To help you understand logical operators, imagine a conversation between a young boy called Steven and his mother. He wants to play on the computer, so he asks his mother, and she says, “You can play on the computer, but only if you do your homework and clean your room.” In programming, you can express this condition using an and operator (&&) between logical values.

fun main() { 
val finishedHomework = false // or true
val cleanedRoom = true // or false
val canPlayGames = finishedHomework && cleanedRoom
println(canPlayGames)
}

Try editing this code in Kotlin Playgrounds and altering the finishedHomework and cleanedRoom values. Then run the code and note how it influences the result canPlayGames value. The canPlayGames is true only if both finishedHomework and cleanedRoom are true. In all the other cases, canPlayGames is false.

fun main() { 
print(true && true) // true
print(true && false) // false
print(false && true) // false
print(false && false) // false
}
a    b    a && b
true true true
true false false
false true false
false false false

Let’s imagine another scenario involving Steven. Say Steven would like to get a puppy. This means that he needs time to look after the puppy because he will be responsible for it. In this scenario, Steven does have time, but he is not responsible enough to have a puppy, so the answer should be no.

fun main() { 
val haveTime = True
val isResponsible = False
val canHavePuppy = isResponsible && haveTime
print(canHavePuppy) // false
}

Let’s take another example. Imagine that you need to verify a percentage value. A percentage has to be any value from 0 to 100 inclusive. You can use the following code to express this.

fun main() { 
val percent = 47
val correct = percent >= 0 && percent <= 100
println(correct) // true
}

The ‘or’ operator (||)

Let’s get back to Steven. He didn’t finish his homework, so he couldn’t play on the computer. But then his friend calls and invites him to go to the cinema. When he asks his mother if he can go, she says, “You can go if you clean the car or cut the grass.” This is how you could create such a condition in programming:

fun main() { 
val carCleaned = false // or true
val grassCut = true // or false
val canGoToCinema = carCleaned || grassCut
println(canGoToCinema)
}

The operator or represents an alternative. It returns true if any of its sides returns true.

fun main() { 
print(true || true) // true
print(true || false) // true
print(false || true) // true
print(false || false) // false
}
a    b    a || b
true true true
true false true
false true true
false false false

Let’s examine some other examples using the or operator.

Let’s say Steven can eat chocolate if he behaves well or cleans his room.

fun main() { 
val behavedWell = false // or true
val cleanedRoom = false // or true
val canEatChocolate = behavedWell || cleanedRoom
println(canEatChocolate)
}

Another example is that the number of a percentage is incorrect if it is smaller than 0 or bigger than 100.

fun main() { 
val percent = 47
val incorrect = percent < 0 || percent > 100
println(incorrect) // true
}

The ‘not’ operator (!)

The last important logical operator is not (!), and it negates the Boolean value. So, it turns true into false and false into true.

fun main() { 
println(!true) // false
println(!false) // true

val isAmazing = true
print(!isAmazing) // false

isBoring = false
print(!isBoring) // true
}

A good analogy for the logical operator not is a minus before a number. It turns a negative number into a positive, and a positive into a negative.

fun main() { 
val positive = 1
print(-positive) // -1

val negative = -1
print(-negative) // 1
}

In programming, you can use negation multiple times.

fun main() { 
println(!true) // false
println(!!true) // true
println(!!!true) // false
println(!!!!true) // true
println(!!!!!true) // false
}

The not operator is often a part of more complex logical expressions. For instance, when Steven’s mom said, “You can play games if you pass the math exam and clean your room.”

fun main() { 
val failedMathExam = true
val roomCleaned = true
val canPlayGames = !failedMathExam && roomCleaned
println(canPlayGames) // false
}

Notice that the negation here only negates the value of failedMathExam, not the result of the whole expression. It is because the not operator has higher precedence than and or operators. So !true && false returns false, because you first evaluate the negation and then false && false. It is similar to numbers. The expression -10 + 20 gives 10 as a result, not -30. To change the precedence, you use parenthesis. So !(true && false) gives true, and -(10 + 20) gives -30.

fun main() { 
println(!true && false) // false
println(!(true && false)) // true
println(-10 + 20) // 10
println(-(10 + 20)) // -30
}

Reading logical expressions

You may find much longer and more complex logical expressions. It helps to read them aloud. You can read it in the following way:

&& as and,

|| as or,

! in front of a value as not and in front of a bracket as it is not true that.

Now practice by reading the following logical expressions out loud:

cleanedRoom && passedTest (should be “cleaned room and passed test”).

!isGrounded || passedTest (should be “is not grounded or passed test”).

cleanedRoom && !passedTest (should be “cleaned room and not passed test”).

!(isGrounded && !passedTest) (should be “it is not true, he is grounded and didn’t pass the test”)

!(!cleanedRoom || !passedTest) (should be “it is not true, he has not cleaned room or not passed test”)

Some logical expressions can be simplified. There is a rule that !(!a && !b) can be replaced with a || b or !(!a || !b) can be replaced with a && b. That means that the expression !(!cleanedRoom || !passedTest) can be replaced with cleanedRoom && passedTest and the expression !(isGrounded && !passedTest) can be replaced with !isGrounded || passedTest.

İbrahim Can Erdoğan

LINKEDIN

YOUTUBE

UDEMY

--

--

ibrahimcanerdogan
ibrahimcanerdogan

Written by ibrahimcanerdogan

Hi, My name is Ibrahim, I am developing ebebek android app within Ebebek. I publish various articles in the field of programming and self-improvement.

No responses yet