*Welcome to “Java Diaries” a series in which I document my self-teaching of Java as both a record of what I’ve done and a reference for me to check back on later – hopefully aiding the information I’ve been consuming to sink in. Click here to view all posts in this series.*

An operator is a character that represents an action, for example + is an arithmetic operator that represents addition.

– BeginnersBook.com

Today’s post will be about the various operators in Java. These operators are, as you can see above, special characters than represent an action.

int myInt = (1 + 2) * 5;

For example in the code above we have have defined an **int **called **myInt **and set it’s value using an **= **sign to (1 **+ **2) ***** 5.

We have three operators in this piece of code:

- = (Assignment)
- + (Plus/Addition)
- * (Multiplication)

Each of these operators perform an action, the **= **assigns the **value** of **myInt **to the outcome of the calculation to its right. Within the calculation the **+ **operator performs the action of adding the **values** of **1** and **2** together. Finally the ***** operator performs the action of multiplying the sum of 1 **+ **2 by 5. This would result in **myInt **being assigned the **value** 15.

When an **operator** performs an action it affects the code either side of it. The code either side of the **operator** is known as the **operand**.

OPERAND:In mathematics an operand is the object of a mathematical operation, i.e. it is the object or quantity that is operated on.– Wikipedia

There are a range of operators, the most common you can see below – for a full list of operators in Java click here.

The basic operator symbols we will use a lot are as follows.

- Assignment =
- Subtraction –
- Addition +
- Multiplication *
- Division /
- Remainder %

We can also combine some of the above operators to create **assignment operators.** These are handy short hand for reducing unnecessary code, take the following code for example:

int x = 0; x = x + 1; system.out.println("X equals = " + x);

We define an **int **called **x **and then **= assign **it a **value** of **0**, we then **reassign x **the **value** of **x + 1 **with the code “**x = x + 1**“. Instead, to speed up the code and reduce the amount of characters we could have typed the following code and it still would have run.

int x = 0; x += 1; system.out.println("X equals = " + x);

Here the line “**x += 1;**” replaces the original line where we redefined **x. **This is in no way revolutionary but over time it seems like a good habit to get into as it will speed up the coding process. The way I think of this example is that **x** is **adding (+)** **1** to what its already **assigned value (=)** .

You can do this with the other basic mathematical operators too.

// We define the int int y = 0; // We perform a calculation int y = y * 10; int y = y - 10; int y = y / 10; // The calculation can be simplfied int y *= 10; int y -= 10; int y /= 10;

Another operator that will be used is the **% remainder **operator. The way the **remainder** is used is it will return the remainder of 2 values after a division has been completed. For example:

int z = 67 % 4; System.out.println(z);

In this instance the system would **print** out the **result** **3**. The full equation behind this is described here by OmniCalculator.com

When you perform division, you can typically write down this operation in the following way:

a/n = q + r/n

Where:

- a is the initial number you want to divide, called the dividend.
- n is the number you divide by; it is called the divisor.
- q is the result of division rounded down to the nearest integer; it is called the quotient.
- r is the remainder of this mathematical operation.

To get this algebra to work inside Java without using **% **would be time consuming and is way above my level (both in coding and mathematics) so I’m glad that **% **exists.

We can also use two operators together to create what is called a postfix operator. These are:

- ++ Increases the value by an increment of 1
- — Decreases the value by an increment of 1

Consider the following code:

package com.danpos; public class Main { public static void main(String[] args) { int z = 0; z = z + 1; System.out.println(z); } }

In this code we have **assigned (=) **the value of **0 **to an **int **called **z. **In the next line we have **added (+)** **1 **to the value of **z **– we then printed the result. We could have instead typed:

package com.danpos; public class Main { public static void main(String[] args) { z = 0; z++; System.out.println(z); } }

This used the **postfix operator “++” **this caused the value of **z **to increment itself by **1.**

In my research I also found you can use **prefix operators** to perform a similar task, by placing the **++ **before the **variable name** you are using. For example the following code would return the **value** of **1** as well.

z = 0; ++z; System.out.println(z);

The above code is still valid, using **prefix operators **I could have also written:

z = 0; System.out.println(++z);

This would have again returned a **value** of **1**.

*Note: Using a postfix operator like this didn’t work. I’m unsure why. For example system.out.println(z++); returned a value of 0;*

The next operators covered were the “**Relational**“, “**AND/OR**” and “**Equality**” **operators**.

Relational

- < Less Than
- > Greater Than
- <= Less than or equal to
- >= Greater than or equal to

Equality

- == Equal to
- != Not equal to

AND/OR

- && And
- || Or

Using these three sets of operators are great for if statements, for example lets use the **relational operator Greater Than or Equal To** (**>=)**:

package com.danpos; public class Main { public static void main(String[] args) { int z = 10; if (z >= 100) { System.out.println("Z is greater than or equal to 100"); } else { System.out.println("Z is less than 100"); } z = 101; if (z >= 100) { System.out.println("Z is greater than or equal to 100"); } else { System.out.println("Z is less than 100"); } } }

In the above code we use an **if statement **to check if **z **is **Greater Than or Equal To (>=) 100**, if it is the program would **print** “Z is greater than or equal to 100”. Inside** **the **else statement** we essentially say if our first test is false (ie, z isn’t greater than or equal to 100) then run this bit of code instead. When running the code above the following happens:

First **if statement**:

- Program checks the
**value**of**z** **Value**of**z**is 10- This
**IS NOT**greater than or equal to (**>=**) 100 - Program prints what is listed inside the
**else statement** - “Z is less than 100” is printed to the screen

Second** if statement**:

- Program checks the
**value**of**z** **Value**of**z**is 100- This
**IS**greater than or equal to (**>=**) 100 - Program prints the first message
- “Z is greater than or equal to 100” is printed to the screen

We can use these three types of operators together too:

int myInt = 100; if (myInt==100 || myInt <=50) { System.out.println("myInt is either exactly equal to 100 or less than 50"); } else { System.out.println("myInt is neither of these"); } myInt = 50; if (myInt==100 || myInt <=50) { System.out.println("myInt is either exactly equal to 100 or less than 50"); } else { System.out.println("myInt is neither of these"); } myInt = 60; if (myInt==100 || myInt <=50) { System.out.println("myInt is either exactly equal to 100 or less than 50"); } else { System.out.println("myInt is neither of these"); }

In this example we have created an **if statement **that will check if **myInt **is either **exactly** **(==)** **100 OR (||)** **Less Than or Equal To (<=) 50**. In the second calling of this **if statement**, **myInt **is **50 **which doesn’t fulfil the first check “**myInt == 100**” but it does fulfil the second check “**myInt <=50**” so the system will print “myInt is either exactly equal to 100 or less than 50”. In the third calling of the **if statement myInt **has been **assigned **the **value **of **60.** This not **exactly** (**==) 100 **and it is *not ***Less Than or Equal To (<=) 50 **so neither the first test **OR (||) **the second test are true to the code inside the **else statement **will be ran, in this case “myInt is neither of these” will be printed to the screen.

Using the **exactly (==) **operator is great for checking certain conditions but sometimes you don’t need to use it, such as when checking the **value **of a **boolean. **If you put the **boolean name **in the **if statement **it will automatically assume you are checking whether **boolean == true **so instead of writing:

boolean isBoolean = true; if (isBoolean == true) { system.out.println("isBoolean is true!"); } else { system.our.println("isBoolean is false!"); }

You could write:

boolean isBoolean = true; if (isBoolean) { system.out.println("isBoolean is true!"); } else { system.our.println("isBoolean is false!"); }

If we then set **isBoolean **to **false**, when the above code ran it would return the **else statement **because **if (isBoolean) {} **is checking whether **isBoolean** is **true** by default.

The last part of today’s lessons we focused on ternary operators.

Interested in saying a lot while writing a little? In a single line of code, the Java ternary operator let’s you assign a value to a variable based on a boolean expression — either a boolean field, or a statement that evaluates to a boolean result.

– AlvinAlexander.com

We create a ternary operator using the operator **?** and **: **characters.

For example:

variable x = (expression) ? value if true: value if false

int a, b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b );

In this example* two **int **variable have been defined, **a** & **b**. **a **has then been set to **10 **and **b **is set a little differently. This is where the ternary operator comes into play. In this example if **a **is **exactly equal to (==) ****1** then the **value **of **b **will be set to **20. **If **a **is *not ***exactly equal to (==) 1**** **then the **value **of **b **will be set to **30. **

Written out in a literal way we are saying: If int a is exactly equal to 1 then set the value of b to 20, else, set it to 30. We could have done this with an if else statement, but this speeds up the coding time considerably by removing code that isn’t needed. Like a lot of these operators they come in handy for code shorthand so it’s good to know all these things.

** This example was taken from TutorialsPoint.*

The final thing I will say about **operators **is that you have to be careful with **precedence. **The below quote sums up the idea of precedence very well!

Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have a higher precedence than addition and subtraction. Precedence rules can be overridden by explicit parentheses.

Precedence order.When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.– Princeton University

In the above quote it states that precedence rules can be overridden by explicit parentheses. So the way we would fix the above equation to perform the addition in the sum first is to write (1 + 2) * 3. You can see the full precedence order in the Java Documentation here or at the Princeton University article quoted above.

I think this sums up the basics of operators, if you want to delve deeper into operators then I can recommend the official Java documentation. See you in the next one!

## Recent Comments