Julia Booleans & Comparisons
A Boolean is either true or false, and its type is Bool. Booleans come from comparisons and are used by if, while and the logical operators.
is_sunny = true
println(is_sunny, " ", typeof(is_sunny))
println(5 > 3)
println(5 == 5.0)
println("apple" < "banana")true Bool
true
true
true
Comparison operators
| Operator | Meaning | Unicode alternative |
|---|---|---|
== |
equal value | |
!= |
not equal | ≠ |
<, > |
less / greater than | |
<=, >= |
less / greater or equal | ≤, ≥ |
=== |
identical (same object or same bits) | ≡ |
isapprox(a, b) |
approximately equal | ≈ |
Julia allows chained comparisons, just like in maths:
x = 7
println(1 < x < 10)
println(0 ≤ x ≤ 5)
println(1 < 2 <= 2 < 3 != 4)
println(0.1 + 0.2 ≈ 0.3)
println(3 ≠ 4)true
false
true
true
true
== versus ===
== compares values; === (egal) asks whether two things are indistinguishable — the same object for mutable values, the same bits for immutable ones:
println(1 == 1.0, " ", 1 === 1.0)
a = [1, 2]
b = [1, 2]
println(a == b, " ", a === b)
c = a
println(a === c)
println("hi" === "hi")true false
true false
true
true
1 === 1.0 is false because an Int64 and a Float64 have different types and bit patterns. Two separately created arrays are equal in value but are different objects.
Logical operators
| Operator | Meaning |
|---|---|
&& |
and (short-circuit) |
|| |
or (short-circuit) |
! |
not |
xor(a, b) / ⊻ |
exclusive or |
Short-circuit means the right side is evaluated only if needed. This is often used as a compact if:
age = 20
has_ticket = false
println(age >= 18 && has_ticket)
println(age >= 18 || has_ticket)
println(!has_ticket)
println(xor(true, false))
age >= 18 && println("adult") # runs, because the left side is true
has_ticket || println("buy a ticket") # runs, because the left side is false
v = Int[]
println(!isempty(v) && v[1] > 0) # safe: v[1] is never evaluatedfalse
true
true
true
adult
buy a ticket
false
Booleans must be Booleans
In some languages, 0, "" or an empty list count as "false". Julia is stricter: conditions in if, while, && and || must be actual Bool values.
try
if 1
println("truthy?")
end
catch e
println(sprint(showerror, e))
end
println(Bool(1), " ", Bool(0))
println(!iszero(1))TypeError: non-boolean (Int64) used in boolean context
true false
true
Booleans are numbers
Bool is a subtype of Integer: true acts like 1 and false like 0 in arithmetic. This makes counting matches easy:
scores = [55, 82, 91, 47, 76]
passed = scores .>= 60
println(passed)
println(sum(passed), " of ", length(scores), " passed")
println(true + true)
println(count(s -> s > 80, scores))Bool[0, 1, 1, 0, 1]
3 of 5 passed
2
2
Test yourself
What is 1 < 3 < 2?
- true
- false
- an error
- 2
What does if 0 ... end do in Julia?
- Skips the block
- Runs the block
- Throws a TypeError
- Converts 0 to false
What is [1, 2] === [1, 2]?
- true
- false
- an error
- [true, true]