Java basics – The operators | Preparing for Java Oracle Associate Certification (OCA) / Java basic technical tests

This article is part of my blog series on how I prepared the OCA (Oracle Certified Associate in Java 8 aka 1Z0-808 exam), make sure to check to other articles if you’re working on it too! These cover basic yet sometimes tricky knowledge about Java which can also help a lot for developer job interviews. You might also want to subscribe to the blog posts to receive next ones directly in your e-mail box.

Also I’m super excited that I’ll be able to take a chance on the Java 11 OCP (Oracle Certified Professional) thank to the Java 25-years-old huge promotion so I plan on writing an article about how to study for next level certification after passing the Associate exam.

This series of articles are meant for people who already know the basics of Java, that is grammar and vocabulary, and knowledge of OOP. The topics covered correspond to OCA Programmer I level and relate to Java 8 version. If you need to learn the basics, I can recommend the JetBrains Academy Java developer track.

Operators

As I realized that the last post was a bit long and covering a lot of topics, this time I’m going to cover only one item which is what’s called “operators” in Java.

The very important thing about operators is to remember the prevalence of each compared to others, that is the order of the operations to perform when facing a mathematical expression.

Basically, that’s learning by heart. Of course, you have to know what each does and how. OCA and other technical tests are pretty much about solving code snippets.

Operators are here listed in the prevalence order, meaning first one prevails over the below mentioned, and so on. When several equally prevalent operators are on the same line, they would be evaluated from left to right.

I’ve added some tips about these, because you won’t be asked to rank them at the exam but to be able to use them, so I described a few tricks from the certification. At the end of the page you’ll find a synthetic chart for clarity.

1. Parentheses

Parentheses beat em all! Just as in math, an operation between ( ) will be evaluated before other operations. So first thing to check is if there are parentheses in an expression.

That’s also a way to safely write an expression when you have a doubt about prevalence (well, for the certification purpose, you can’t have doubts, but when you code… and say you’re tired 🙄 you can sometimes use some help).

It’s super important to remember that rule not only for mathematical operations, everything isn’t about numbers (thank goodness). When casting, parentheses are sometimes mandatory. Method calls (object.method()) would be evaluated first except if there are some parentheses.

Concretely, these two expressions are different and one is likely to fail if your logic is well implemented:

Frog animal.jump();
(Frog animal).jump();

First case, animal calls the jump method and the casting kind of serves nothing, in the second case animal is casted to Frog and then the frog can jump. (Happy I didn’t use the same old cat-dog or lion-antelope example?)

Ok, now let’s learn by heart the order of the other operations:

2. Post-unary

Yeah, there is a hierarchy between pre- and post-unary operators, and the latter comes first. Post-unary operator increments or decrements a numeric value by 1:

int a = 2;
a++; // a = 3
a--; // a = 2

In certifications and tests you will get a lot of questions with post- and pre-unary operators because they want to make sure you understand the difference. What’s the difference you ask? They both increment/decrement by 1, but while post-unary does it after evaluation, pre-unary does it before evaluation.

int a = 10;
int b = 5;
int c = b++ + ++a; /* at evaluation, b = 5 and a = 11, so c = 16, but right after b = 6 */
int d = b; // d = 6, b = 6

I swear you will get a lot, I mean A. LOT., of these in the Java certifications, so this has to be crystal clear in your head!

Now, code snippets at the certification are way longer with possible tricks about code not compiling or throwing errors, messing with prevalence, possibly using wrong type inference or castings. You gotta have fun.

3. Pre-unary

Oh common, I just explained it.

4. Unary operators

Unary operators operate on one variable or value alone.

They are the… signed signs? signing signs? whatever, the + and – signs, but not to confuse with addition and subtraction!!!, as well as the NOT operator ! and the bitwise complement ~ which is not in OCA so I’ll talk about it in the article about upgrading to OCP.

So you have to remember: + – ! , and that these + and – are not the addition and subtraction signs.

5. Multiplication, division and friends

Multiplication *, division / and modulus %.

6. Addition and subtraction

Now, + and – signs for addition and subtraction, not to confuse with signing signs which have higher prevalence.

7. Shift operators

That’s not OCA but OCP, but you might already want to remember where they belong in the ranking. They look like <<, >> and >>> and… well I’m studying them now so I’ll tell you in the article about upgrading to OCP certification.

8. Relational operators

Those are the comparison operators (harder better strong faster bigger than > smaller than < bigger than or equal >= smaller than or equal <=), and “instanceof” (beware of the case, all lower!).

The first ones are pretty simple (of course there will be tricks about their use in loops at the exam).

Up to Java 14 (so far, certifications cover Java 8 and 11 so we’re good), this is how to use instanceof:

  • left hand side must be a reference type
  • right hand side is a Class, Interface or Enum (not an instance, a Class!)
  • so you may write animal instanceof Frog for example
  • it returns a boolean
  • you will likely get questions involving inheritance, remember that instanceof can be translated to IS-A, so child reference IS-A Parent class is working; so if you coded your logic well, you would likely get true when testing froggy instanceof Animal

Ok, where were we?

9. Equality

== and !=, not to confuse with simple assignment sign =.

This is also trick material. Always double check the number of equal signs in boolean expressions!

if (myBool = true) {
   // THIS WILL BE REACHED!
}

Ok, what witchcraft is being used here? Parentheses are evaluated first. Inside the parentheses, there is an assignment. The variable myBool is being assigned value true. Then the IF statement tests the expression, which equals true, then enters the block.

So both == and = can be used in the parentheses (assignment would only compile if it’s a boolean value), even though second case is really bad practice and probably an error in real life situation. But they do like it in the certification.

Equality operators can be used with numeric, boolean or Object (reference) types, but those types cannot be mixed in the same expression: you cannot compare a numeric with a boolean or an Object (unless that case is implemented like with the wrapper classes but that’s one exception that can be perfectly explained).

Don’t forget that they will compare Objects’ addresses if equals is not overriden, same for Strings.

If two instances are null, the comparison will return true (default implementation).

10. Logical operators

Wow, Java does have quite a few operators… Almost there but still a few to go.

Logical operators are, I think, rarely used, or for very specific logic needs (networking I’d say). They are pretty trick. They look like other operators you know, but they act pretty weird.

& (AND), | (OR) and ^ (XOR) are particular in that they can be used with numeric values and boolean ones (not mixed, all operands must be numeric or boolean). When used with numeric values, they perform an operation on the bits, which is out of scope for OCA as far as I remember.

When used when booleans, they have the particularity not to short-circuit evaluation. This means that the OR operator will evaluate both sides even if first expression satisfies true, and AND will evaluate both sides even if first expression returns false. XOR as to check them both anyway.

AND will return true if both sides are true, OR will return true if one or the two expressions are true, and XOR will return true if only one is true and the other one is false.

I’ll show some examples of AND and OR operators below. Just to make it extra clear about XOR :

  • true ^ true = false
  • true ^ false = true
  • false ^ false = false

11. Short-circuits

Those are way more used, you cannot learn coding in Java without using && and ||. They are called short-circuits because they won’t go further if left-hand side doesn’t satisfy the requirements.

So at the exam, they will try to trick you with operations on the right-hand side. Here a dummy example:

boolean doStg() {
 System.out.println("Hey you!");
 /* it could also be some code that changes values that you'll have to use later! */
 return true; // makes no sense, I agree
}

true && doStg(); // Hey you!
false && doStg(); //
true & doStg(); // Hey you!
false & doStg(); // Hey you!
false || doStg(); // Hey you!
true || doStg(); //
false | doStg(); // Hey you!
true | doStg(); // Hey you!

First, && operator needs both sides to return true, to return true itself. After checking left-hand side with satisfies the condition, it continues with right hand side. In the second case, the left-hand side doesn’t satisfy the condition, and because we use short-circuit operator we don’t need to check further. So doStg() is not called.

Then third line, without surprise the result is the same as first line because both sides are true. Then the tricky one, fourth line left-hand side is false, but as we don’t use short-circuit right side will still be evaluated, so doStg() gets called. And same with the OR operators.

Again, this is very bad code practice IRL, but you will see it in exercises to test how well you master your stuff. You can remember that non-short circuit operators will evaluate both sides, sometimes that’s all you need to spot to solve the problem.

12. Ternary

The powerful ternary expression, which best use is to assign a value depending on a condition. It can be used to trigger method calls and any other action, and it can be nested on N-levels, which can become pretty dirty to read, but you know… they will try to trick you at the exam…

boolean expression ? result if true : result if false;

where true or false or both can be another ternary expression.

Only the true or false statement of each statement is evaluated (kind of like short-circuit) so be careful of operations or assignments inside the expressions (including method calls).

Expressions must return a value, whose types can be different, but they cannot return void (for example you don’t call a console output method there).

13. Assignment

Finally, assignment operators. The ones you have to be able to use for the OCA exam are = += -= *= /=.

An assignment returns the assigned value.

Tricks about the compounds assignment operators: the variable must already be initialized, and the result is casted implicitly to the type of the first operand!

You might want to know that a few other exist, that are covered by the OCP exam: &= ^= |= <<= >>= >>>=.

Table of the Java operators prevalence for OCA

parentheses()
post-unaryx++ x–
pre-unary–x ++x
unary+ – !
multi/division* / %
add/subtraction+ –
relational< > <= >= instanceof
equality== !=
logical& | ^
short-circuit|| &&
ternarybool ? if true : if false
assignment= += -= *= /=

Numeric promotion

A short yet important topic related to operations is numeric promotion. Here are the rules you have to know:

  • if two numeric values have a different data type, there’s an automatic promotion to the larger of the two types. If you add a long value to an int value, result must be held in a long value (except if you use explicit castings of course);
  • if one value is integral and the other is floating, the promotion is made to the floating point type;
  • smaller types (byte, short and char) are automatically promoted to int anytime they’re used with binary arithmetic operators, even if neither of the operands is an int.

The point is at the exam they will try to trick you by using the wrong type to hold the result, which would cause compilation error.

3 thoughts on “Java basics – The operators | Preparing for Java Oracle Associate Certification (OCA) / Java basic technical tests

Leave a Reply

Your email address will not be published. Required fields are marked *

Don’t miss out!

Receive every new article in your mailbox automatically.


Skip to content