# Chapter:Expressions and operators

Expand using link to the right to see the full content.

### Introduction

Calculating the age of a person would be hard to do without using the - sign. Programming languages provide us with the most used mathematical operations, such as plus and minus using a special character (or symbol, token) to make them easy to use. These are referred to as operators. Some operators have the form of more than one character (e.g. the equality token ==, the increment operator ++ etc).

Expression is in the simplest form easy to understand. We will start from some simple examples and continue with a bit more complete definition of expression. It is not possible to give a complete definition of expression without knowing what a method or operators etc are so we will settle for a limited definition of expression and extend the concept as the course progresses.

#### Purpose

There would not be much of a program if we didn’t have operators. The purpose of this lecture is to introduce the student to operators. The knowledge gained from this lecture provides a foundation for coming lectures.

Expression are used all over programs. After a while, expressions become natural and not something one need to think about that much, still this introduction to expressions is good for the coming lectures.

### Requirements

#### Goal

The student shall:

• be familiar with the operator concept.
• be able to use operators when writing programs
• be able to use expressions in variable assignment and in other places in a program
• understand the role of the type of an expression

### Instructions to the teacher

#### Common problems

Expressions are very important to understand. Without this understanding we have found it hard for the students to:

• understand method calls and their argument lists
• understand pointers (in languages having those) and reference variables
• understand the order of evaluation in statements using expressions (such as assignment statements)
• understand nested method calls (when the argument to a method is the result of calling another method)

Our experience is that it is time well spent to stress that expressions are evaluated before being used. Understanding this makes it easier to understand a simple statement such as assigning a variable the result of a method call. It's a good idea to come back to this and repeat that assignment statements have a left-hand side (with the variable to be assigned) and a right-hand side with an expression for the value the variable will be assigned.

Be aware of the fact that the type of a compound expression (with operators and operands) depends on the types of the operands according to a set of rules. At this stage, it is enough to focus on whole (integer) division (and its remainder companion) when the operands are both integral, and contrast that to real division when (at least one of the) operands are of real types.

It may also be confusing to students what type a literal will have (e.g. that integral literals have type int while floating point literals have type double).

If the students ask, refer to The Java Language Specification, §5.6.2 - Binary Numeric Promotion.

## Chapter videos

### All Swedish videos in this chapter

See below for individual links to the videos.

## Operators

### Description

Operators are constructs found in a programming language. These operators correspond to some kind of functionality, which can be mathematical or of some other kind. One simple example of operators is `+`, which can be used to add two integers (these integers are then called operands) like this:

```int a;
a = 3 + 7;
```

Sometimes an operator has different meaning depending on the context. This is called overloaded operators. In Java, for instance, you can put two strings (and actually a String and an expression of another type) together with the `+` operator, like this:

```String s;
s = "Hi " + "there!";
```

s now refers to a new String with the value "Hi there!". Joining to Strings together is called concatenation by college professors.

Another common operator which you have seen already is the assignment operator `=`. It is worth mentioning that using operators in an expression creates a type related to the operator used. For instance, a comparison between to variables using the > (greater than) operator like this: `a > b` yields a boolean type expression (which can be used in an if-statement for instance).

Some operators require two "operands" (values the operator operates on). Such operators are placed in between the two operands such as `+` in `a + b`. Some people and literature calls such operators "binary" "infix" operators (binary referring to the two operands needed, infix referring to the position in the middle). Some operators require only one operand and are called "unary" operators. A simple unary operator is `-` (minus) which changes the sign of an expression: `negativeA = -a;`

### Presentation

Presentation: Operator (pdf)

### Videos

Operator (eng) (swe)

## Expression

### Description

In its simplest form an expression is a literal (e g 0). In the code below we assign the variable `a` the value 0. 0 is a literal but as such also an expression.

```int a;
a = 0;
```

If we combine two literals with an operator:

```int a;
a = 0 + 12;
```

we get a slightly more complex expression. So for now an expression is either a `literal` or a combination of two literals and and an operator, like this: `literal operator literal`.

How about `0 + 12 - 7`. Is that an expression?

It is, if we want to change `literal operator literal` to be `expression operator expression`. This means that an expression can contain other expressions.

Let's analyse `0 + 12 - 7` a bit. We know from before that `0 + 12` is an expression. This means that `0 + 12 - 7` can be written as `expression - 7` which we now see itself is an expression. So `0 + 12 - 7` is a valid expression.

### Presentation

Presentation: Expression (pdf)

### Videos

Expressions (eng) (swe)

## Types of operators

Q: “What types of operators are there in the Java programming language?”
A: One way of grouping operators together is by looking at the type of the value they produce. For instance, there are operators that produce `boolean` values like comparison operators and `boolean` operators. Comparison operators take numeric operands in the form of a claim about the relation between two values: a < b

The claim that the value of a is smaller than the value of b is either a true claim or a false claim. Therefor the value of the expression a < b has the type `boolean` (which only allows two values, `true` or `false`).

These are the comparison operators:

• `<` "less than"
• `>` "greater than"
• `<=` "less than or equal to"
• `>=` "greater than or equal to"
• `==` "equal to"
• `!=` "not equal to"

They all work on numeric operands, like `int` or `double`, for instance:

```int age = student.age(); // student refers to an object of class Student
// we can ask the student for its age as an <code>int</code>
// by sending the message age() via the reference.
// This is also known as calling the instance method age().

// By comparing the age variable to 17, we get a boolean value, indicating
// whether the student was adult or not:
boolean isAdult = age > 17; // comparing two int values produces true or false of type boolean
```

## Boolean operators - produce a boolean value from one or more boolean operands

The boolean operators also produce a boolean value but the operands have to be boolean values as well. If we have two boolean values; `isRaining` and `isStormy`, that hold the state of the weather (if `isRaining` is `true`, it is raining, if `isStormy` is `true` it is stormy), than we can combine them using a boolean operator such as `&&` (meaning AND). If we use the `&&` operator with the variables as operands, we would say for instance

``` isRaining && isStormy
```

which also would be a claim about the weather which would be `true` or `false`. Only if both `isRaining` and `isStormy` are true, the claim that it “`isRaining && isStormy`” would be `true`! (And it would also probably be wise to wear a raincoat instead of bringing the umbrella.)

The boolean operators are (for instance):

• `&&` "AND"
• `||` "OR"
• `!` "NOT"

The boolean operators produce a boolean value, and the operands are boolean values or expressions:

```boolean isAdult = age > 17;

boolean isAdolecent = !isAdult; // using NOT produces the opposite truth value of a boolean expression.

// We can combine boolean expressions with the operator ||
boolean isWeekEnd = (day == SATURDAY) || (day == SUNDAY);

boolean isWorkDay = !isWeekEnd; // workdays are NOT week-ends!

// We can combine boolean expressions with the operator &&
boolean isWorkHour = isWorkDay && ( hour > 8 && hour < 17 );

// The parentheses aren't necessary but makes it easier to read the expressions
```

## Arithmetic operators

For numeric types we can also use operators which produce new numeric values. That would be the arithmetic operators which take operands which are also numeric such as addition, subtraction, multiplication and division. We also have remainder (which produces the left over from integer division).

The arithmetic operators are (for instance):

• `+` "plus"
• `-` "minus"
• `*` "times"
• `/` "divided by"
• `%` "remainder" NOTE: this has nothing to do with percent!

## The `new` operator

To produce references (addresses to objects we could say) we use the `new` operator (`new` is also a Java keyword and reserved word). We have seen that in a previous chapter when we produced brand new `Greeter` objects using the `new` operator (and a named constructor).

## The assignment operator

A special kind of operator is the assignment operator. It always has a variable as the left-hand operand and an expression as the right-hand operand. But what type of value does it produce? It produces the same value as the right-hand side, actually (and the same type). So, in theory, we could use an assignment as an expression and put it on the right-hand side of another assignment like this for instance:

``` numberOfLinesBackup = ( numberOfLines = firstBatch + secondBatch );
```

This is actually also possible in practice but we advise you not to use this style. Much clearer if you divide the above into two assignment statements instead.

Above we have seen some of the operators grouped together by the type of value they produce.

## Other ways to categorize operators

Q: “What other way could we use to group operators?”
A: We could, for instance, look at the function or purpose of operators. We could say comparison operators, assignment operators, logical operators, arithmetic operators etc. How we group the operators may not be the most important aspect for understanding operators however. We have to understand that operators are applied to form expressions and to produce values of some type. Sometimes the type of the expression is the same as the parts (operands) of the expressions and sometimes not.

What we haven’t talked about is the number of operands an operator requires. There are two basic categories here: unary operators and binary operators. Unary operators are applied to one single operand. Examples of this is sign operators ( `+` and `-` ). If we want to change the sign of the value of a variable we could use `-` (the minus sign) like this:

``` int warm = 30;
int veryCold = -warm; // -30 is very cold
```

The `-` operator used like this operate on a single operand (in the example the variable `warm`). So `-` used like this is a unary operator. Used like a unary operator, the `-` sign must be applied before the operand. You cannot say “`warm -;`” for instance.

Unary operators that are applied before the operand are called prefix unary operators. Does people talk like that, you may wonder? Well not everybody, but people at universities and people writing books about programming like to use words like that. You don’t have to learn all the technical terms, we are just discussing different types of operators and their number of operands and the position of the operand of operators with only one operand.

Other examples of unary operands include `!` (the exclamation mark is used as meaning NOT and is a `boolean` prefix unary operator). The NOT operator can be used like this:

``` !isRaining
```

Used like that requires `isRaning` to be a `boolean` type variable and would have the effect of negating whatever value `isRaining` might have. The value produced is of `boolean` type of course, since we should consider it a claim meaning “not is raining” which is `true` on a sunny day but a `false` claim most days in Göteborg (where it is raining a lot).

The increment and decrement operators `++` and `--` can be used both as prefix (before the operand) and postfix (after the operand). There is a difference between these two positions in the way the expression is evaluated. As all operators, the increment and decrement operators produce a value when applied to their operand. But they also have a side-effect, in that the operand (which always is an integer type variable) changes its value (up one for increment and down one for decrement). When applied as a prefix operator (before the variable operand) the change of value happens before the value of the expression is produced. When applied as a postfix operator (after the variable operand) the value produced of the expression is the old value of the variable, and only then, after the expression is evaluated to a value, the change of value takes place.

```int i = 0;
int j = i++;

System.out.println("i: " + i); // prints 1
System.out.println("j: " + j); // prints 0 // increment of i happened after the assignment.

j = 0;
i = 0;

j = ++i;

System.out.println("i: " + i); // prints 1
System.out.println("j: " + j); // prints 1 // increment of i happened before the assignment.

// -- works in the same way:
i = 1;
j = --i;
System.out.println("i: " + i); // prints 0
System.out.println("j: " + j); // prints 0 // derement of i happened before the assignment.
```

Binary operators, on the other hand, require two operands, on on each side. The `*` operator (asterisk or star) is a binary operator. The operator is in the middle of the two operands, and some people like to call this an “infix” operator. You don’t have to call it that, though.

Finally, there is one ternary operator (or operator pair) in Java. The operator has two symbols, ‘`?`’ and ‘`:`’ (question mark and colon). It is used as a short form for making decisions. The operands are three. First there is a `boolean` expression followed by the question mark. Next, there is an expression which is to be the value produced if the `boolean` expression was `true`, next there is the colon followed by and expression which is the value to be produced if the `boolean` expression was `false`. This requires an example, probably:

``` Boot myBoots = isRaining ? Boots.WELLINGTONS : Boots.REGULAR_BOOTS;
```

Video about ternary: Java Ternary operator (pdf)

In the example, we pretend we have a type `Boot` (which is described somewhere, perhaps in a class defined in a file `Boot.java`) and a reference variable `myBoot`. We want to decide what type of boot it should be and let the variable `isRaining` decide for us. If it is raining, Wellington boots are suitable. Otherwise, we go for regular boots.

## Separators

Q: “I have seen some other symbols in the example programs you have shown us. They include:
` ; . ( ) [ ] { } , `

Are those too operators?
A: Well, no. They are very similar to operators but we call them separators. They are used to... well... separate parts of our program from other parts. We can talk a little about some of them, in particular the ones we have seen being used in practice. First we have the semicolon `;`

The semicolon is used to terminate an instruction (a statement). To the Java compiler it means “Here ends one instruction”. Next, we have the dot `.`

The dot is used in a few ways. One way it is used, is to form the separator between directories in a package path. We’ve seen it in the form `import lib.Greeter` . The dot between `lib` and `Greeter` means that `lib` is a directory and in that directory we find `Greeter` (which is a class).

The parentheses are used to group parameters when we define a constructor or a method. They are also used to group the values we give as arguments when we call a constructor or a method. Client code (like the code we saw in the main method) calls a constructor in some class and use the parentheses to group any arguments (supplied values) that we might want to send along. The same thing applies when we call a method. Client code might want to call a method defined somewhere and we use parentheses to group any arguments we might want to send along.

The square brackets `[ ]` have to do with lists of values (such lists are called arrays in Java - more on that later!). We’ve only seen it in the definition of the main method:

``` public static void main(String[] args)
```

The use of a list (called an array) of String in the main method’s parameters means that it can be called (by the JVM) with zero or more String arguments. We don’t know yet how to use arguments to the main method, so this probably sounds abstract. Don’t worry. We’ll see examples of that later in the course. For now, just think that you can send along values to a method. Arrays can be used to let us send any number of values packed as a list (which may be empty - or even no list at all).

The curly braces are used to form blocks of code. Typical blocks include a class definition, a constructor definition, or a method definition. There are actually a few other types of blocks but we haven’t seen them yet so we leave that for a later day. The comma `,` is used when we list things. It could be contents of an array (example of that later in the course), or a list of values that we send as arguments to a method. When declaring a method that can accept for instance two arguments, we define the parameters separated by a comma.

``` public static long add(int a, int b){ ...code adding a and b... }
```

That’s actually how we could define a method that takes two int values as arguments. Not that we declare the parameter variables `a` and `b` separated by a comma. You will soon learn more about methods, so please be patient.