Tutorials
Blog
About

Tutorials > Julia Programming: a Hands-on Tutorial

Boolean Variables

by Martin D. Maas, Ph.D
@MartinDMaas

Last updated: 2021-10-25

Logical Operators

Boolean variables true and false are quintessential to computer programming. Let’s describe the basic boolean operations implemented in Julia:

Operator Syntax Description
not !x negation
and x && y returns true if both operands are true
or x

Importantly, && and || are short-circuited (see Wiki).

This has a series of advantages. In particular, we can do

if a > 0 && expensive_computation(b) > 0
    do_something()
end

In this way, we avoid performing the expensive computation if it’s not necessary (when a>0 returnes false).

Also, you won’t get a nasty error when doing something like

if @isdefined(ge) && ge>0
    print("ge exists and is greater than 0")
end

because trying to assess whether an undefined variable is greater than zero is usually not permitted in any programming language.

As for the ‘or’ operator, the fact that it is short-circuited means that it will return true if the first expression is true without the need to evaluate the second. This can also lead to performance gains.

if 3 > 2 && expensive_computation(b) > 0
    do_something()
end

The expensive_computation function won’t be called, as the first expression returnes true.

Logical to Number

In Julia, Bool is a subtype of Integer. true equals 1, while false equals zero. In particular, we can do numerical operations on Bool types without the need of any type conversion.

true + true         # 2

Ask me a question or send me your comments!

Don't hesitate to ask me any question about the topics I cover on this blog!

Click here to reach out!