So far we've only looked at some fairly simple control structure conditions, by this I mean we've seen things like:

if (age < 13)
{
  System.out.println("You are a child.");
}
else if (age < 20)
{
  System.out.println("You are a teenager.");
}
else
{
  System.out.println("You are an adult.");
}

This works well if you don't have a very complicated system to work with, but if you're building a real application, then chances are you'll need to make use of more advanced Java Operators!

What is a Java Operator

A Java operator is the symbol that you put in the conditional statements of your control structures (for the most part). There are other examples of when you could use certain Java operators, but I'll touch on those at the end of this Java tutorial. So, for the example above, the operator we are using is the “less than” operator (<). So then you could probably guess that there is also a “greater than” (>) operator right? Right! You've probably seen me use it in other tutorials, but what else have you seen? Here's a list of some common Java operators:

Equality and Relational Operators

Operator Description
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

These should seem fairly straight forward to you, so I'll skip right into the conditional Java operator…

Conditional Operators

Operator Description
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for
if-then-else statement)

Now these conditional operators are more interesting, as they allow you to put many operators together… here's an example of how they'd be used:

if ((age > 0 && age < 13) || (age > 19))
{
  System.out.println("You are not a teenager");
}
else
{
  System.out.println("You are a teenager");
}

Here I used three different relational operators (less than and greater than) and sprinkled in two conditional operators (&& and ||) all in one control structure (if statement). Now here's a curve ball, you can also throw in the use of the NOT (!) operator. This will reverse the boolean logic of any statement. If we were to apply a NOT to our example above, we would have to change the System.out statements like so:

if (!((age > 0 && age < 13) || (age > 19)))
{
  System.out.println("You are a teenager");
}
else
{
  System.out.println("You are not a teenager");
}

You see how I added that NOT (!) symbol in the IF statement? I added yet another bracket that surrounds the ENTIRE if condition. The way you would read this is to determine what would happen without the NOT logic first, THEN just reverse your output. So if the age variable was 14, I would say, “Is 14 > 0 and is 14 < 13” , “OR is 14 > 19”? In this case I would say NO, none of these statements are true, BUT we then need to switch the outcome because we have a NOT (!) operator that wraps our entire logic, so our NO turns into a YES (or true), so the output would be “You are a teenager”… which is true, if you're 14 then you're a teenager.

Be careful when using the NOT (!) operator, as it can sometimes make figuring out the logic quite complicated. Here's a good example of over-use of the NOT (!) operator to over complicate an if statement:

if (!(age > 0) || !(age < 13) && !(age > 19))
{
  System.out.println("You are a teenager");
}
else
{
  System.out.println("You are not a teenager");
}

Believe it or not, this logic is still valid (I know, because I tested it!). But it's so confusing to read, so please, for the sake of all developers out there, avoid using the NOT operator if you can.

Now, there was one more conditional operator in that chart above that I haven't talked about yet, and that's the ternary operator!

Ternary Operator (also a Conditional operator)

This Java operator is another one of those operators that you should only use when it'll result in code that's easy to read. Someone could easily get carried away with using these ternary operators and it just makes the code almost unreadable…

Having said that, let me show you what this ternary Java operator does!

Using the ternary operator is a shortcut for writing an “If true do this, else do that” block of code. So if we go back to our teenager example that we've already seen:

if ((age > 0 && age < 13) || (age > 19))
{
  System.out.println("You are not a teenager");
}
else
{
  System.out.println("You are a teenager");
}

This code can be re-written using the ternary operator like so:

boolean isTeenager = ((age > 0 && age < 13) || (age > 19)) ?
System.out.println("You are not a teenager") : System.out.println("You are a teenager");

Now this looks pretty busy, so let me show you a basic version of what this ternary operator looks like:

boolean isAnAdult = (age > 19) ? true : false;

So all this ternary operator does is evaluate the condition before the question mark, and if the condition evaluates to true then it will assign the value to the left of the colon to our boolean variable. If the condition evaluates to false, then it'll assign the value to the right of the colon to our boolean variable.

So in our more basic version, we evaluate the condition before the question mark (age > 19). So let's say age = 20. It would say, “is 20 > 19?”, yes, then assign the value on the left of the colon to our variable. So what's to the left of the colon? The boolean value true, so this would be assigned to our isAnAdult variable. In the reverse case, if age = 13, then we evaluate the condition “is 13 > 19?” nope, so then we assign the value to the right of the colon, which in this case is false.

Again, this is just a shortcut way to write code, as the isAnAdult code could just be written as:

boolean isAnAdult;
if (age > 19)
{
  isAnAdult = true;
}
else
{
  isAnAdult = false;
}

So, 9 lines of code versus 1 line of code. Some would say that using ternary is better because you write less code, but, I would say that you should only use the ternary operator if your code is easily readable. If it isn't, then I would favour MORE lines of code to be more clear.

Arithmetic Operators

Operator Description
&& Conditional-AND
+ Additive operator (also used
for String concatenation)
Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

These arithmetic Java operators are also pretty straight-forward. You've seen that the + operator can be used to add two numbers together OR to concatenate two Strings together (in the Strings Java tutorial). Subtraction, division and multiplication are all self explanatory, these are used for mathematical operations (just like using a calculator!). But, one thing you haven't seen is the remainder operator. So what's that all about?

Remainder Operator

This is used to determine what the remainder is in a division operation. For example, what's 15 divided by 7? Well, it's 2 with a remainder of 1. What's 7 divided by 8? It's 0 with a remainder of 7! This is what the remainder operator (%) tells you, just the remainder of a division operation. So what does it look like when used in code?

Integer remainder = 833 % 28;
System.out.println("remainder is: " + remainder);

This would output 21. Pretty easy right? 833 / 28 = 29, with a remainder of 21. So the remainder variable gets the value of 21, and we output it!

So now the question is, what's a real world scenario for the use of the remainder operator? Well, I've really only seen it used for displaying rows of a report in a nice way. What I mean by that is you'll have a report printing on the screen and each row of the report will alternate their background colours (between white and grey). This is accomplished by using the remainder operator, sort of like this:

Integer numberOfRows = report.getNumberOfRows();

for (int i=0; i<numberOfRows; i++)
{
  BackgroundColor bgColor = (i % 2 == 0) ? "white" : "grey";
  // then we would use this bgColor for the reports output
}

So in this example we used the remainder operator inside a ternary operator. What will happen here is that as we go through each of the rows, the variable i will increment. Here's what each iteration would look like:

i (i % 2 == 0)? bgColor
 0 true white
 1 false grey
 2 true white
 3 false grey
 4 true white

So you see what happens as a result? You get alternating white and grey background colours, which makes reading reports much easier, as it lines up each of the rows for you :) Kinda nifty right? Okay not really, but still, it's a great example for the use of the remainder operator!

Unary Operators

Operator Description
++ Increment operator; increments
a value by 1
– – Decrement operator; decrements
a value by 1

You've seen me use these before in my for loops. This is yet another shortcut way of writing code, and this is best explained with a code example:

int i = 0;
i = i + 1;
// what does i equal now?
// well since i = 0, it's saying i = 0 + 1
// so now i equals 1
i = i + 1;
// what does i equal now?
// well now, since i = 1, it's saying i = 1 + 1
// so now i equals 2
i++;
// what does i equal now?
// well now, since i = 2, it's saying i = 2 + 1
// so now i equals 3

You see? saying i++ is the same as saying i = i + 1. Piece of cake!

Now you might ask, is there a shortcut way of writing something like i = i + 238, why yes… yes there is!

int i = 0;

i += 238;

// now i = 238, because this is the same thing as saying
i = i + 238;

So, all of these shortcuts are the same for subtraction, division and multiplication as they are for addition (with the exception of ** and //. ** doesn't mean anything, and // is used to write in comments as you've seen already. But i *= 10 is valid, it just means i = i * 10. Or i /= 15 which is the same as i = i / 15. You get the idea.

These shortcuts are ones that I would always recommend using, as they don't make the code less readable in my opinion. I've never had a problem understanding what anyone meant when they were used.

For the sake of completion

There are also operators known as “Bitwise and Bit Shift Operators”. I don't really want to talk about them, as it would be a somewhat confusing topic for me to cover at this point in your learning, and I don't think you would get much out of it, as these operators are not used very often in the real world. If you DO feel like bonus points and you want to learn about these operators, check out roseindia's tutorial.

Summary

Wow, that's a lot of operators and shortcuts! These Java operators are (for the most part) very commonly used in the Java programming language and I think you'll become very comfortable with them as you program with Java. It's also a very universal topic, so you'll be able to carry this knowledge around in other programming languages if you choose to learn another one. So it's definitely worth learning :)

Alrighty, so, as always it's a pleasure and a privilege to teach you guys everything I know about Java, and I'd love it if you could do me the favour of sharing the love. So could you please share this Java tutorial with everyone you know by clicking the like/tweet/stumble/g+ buttons on the top left of your screen? It helps to let the world know about my website and (in the case of Google+) it helps my Google search rankings so that even MORE people can find my site and learn this great content. And if you're feeling really generous, please head over to iTunes and give my new podcast a rating (it helps the podcast get found in iTunes!).

Thank you so much and I hope you are loving learning Java! Take care.

 

Free Java Beginners Course

Start learning how to code today with our free beginners course. Learn more.