🎓 A1Learner
🔍
0 of 52 lessons completed

Julia Boolean Logic

Boolean logic combines Bool values into a single Bool result. Julia uses three small operators for this combining.

And needs both sides true

The && operator combines two Bool values. Only the pairing of two true values gives true.

println(true && true)
println(true && false)
println(false && false)

Or needs one side true, and not flips

The || operator gives true when either side is true. The ! operator flips the value in front of it.

println(false || true)
println(false || false)
println(!true)
println(!false)

Logic on comparison results

A comparison gives a Bool, so comparisons can be combined directly. Each side is worked out first, then the logic operator combines the two results.

println(3 < 5 && 2 < 4)
println(3 > 5 || 2 < 4)
println(!(3 == 3))

Example

ready = true
awake = false
println(ready && awake)
println(ready || awake)
println(!awake)
println(ready && !awake)

Key points

  • Bool values: a Bool holds exactly one of the two values true and false.
  • And: && gives true only when both sides are true.
  • Or: || gives true when at least one side is true.
  • Not: ! flips a Bool, turning true into false and false into true.
  • Stored results: a combined result is a plain Bool and can be stored in a variable.

In this example, ready is true and awake is false. The first line combines them with && and gets false, the second combines them with || and gets true, the third flips awake to true, and the last line is true because ready is true and awake flipped is also true.

Note

the operators work on Bool values, so a comparison result can feed straight into them.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What does println(true || false && false) print if && is worked out before ||?