Operators And Statements Java 8 Certification

Operators and Statementsis the next important chapter for when appearing for OCA (Oracle Certified Associate Exam 1Z0-808), (or for Java 8 Certification). You must understand the Operator and Statementfundamental. This section covers following topic in detail so you can understand them and use them to answer question during java certification exams.

Before we deep dive on Java building blocks, I would like to list down the topic which I am going to cover it here

Using Operators and Decision Constructs

  1. Use Java operators; including parentheses to override operator precedence
  2. Create if and if/else and ternary constructs
  3. Use a switch statement.

Using Loop Constructs

  1. Create and use while loops
  2. Create and use for loops including the enhanced for loop
  3. Create and use do/while loops
  4. Compare loop constructs
  5. Use break and continue

Read the full java certification syllabus article by clicking here.

Understanding Java Operators

A Java operator is a special symbol that can be applied to a set of variables, values, orliteralsreferred to as operandsand that returns a result. Three flavors of operators areavailable in Java: unary, binary, and ternary. These types of operators can be applied to one, two, or three operands, respectively. For the OCA exam, youll need know a specific subset of Java operators, how to apply them, and the order in which they should be applied.Java operators are not necessarily evaluated from left-to-right order. For example, the following Java expression is actually evaluated from right-to-left given the specific operatorsinvolved:

int y = 4;
double x = 3 + 2 * --y;

In this example, you would first decrementy to 3, and then multiply the resulting valueby 2, and finally add 3. The value would then be automatically upcast from 9 to 9.0 andassigned to x. The final values of x and y would be 9.0 and 3, respectively. If you didnt follow that evaluation, dont worry. By the end of this chapter, solving problems like thisshould be second nature.

Unless overridden with parentheses, Java operators follow order of operation

  1. Post-unary operators expression++, expression--
  2. Pre-unary operators ++expression, --expression
  3. Other unary operators +, -, !
  4. Multiplication/Division/Modulus *, /, %
  5. Addition/Subtraction +, -
  6. Shift operators , ,
  7. Relational operators , , =, =, instanceof
  8. Equal to/not equal to ==, !=
  9. Logical operators &, ^, |
  10. Short-circuit logical operators &&, ||
  11. Ternary operators boolean expression ? expression1 : expression2
  12. Assignment operators =, +=, -=, *=, /=, %=, &=, ^=, !=, =, =, =

Working with Binary ArithmeticOperators

Binary operatorsare commonly combined in complex expressions with more than two variables; therefore,operator precedence is very important in evaluating expressions

Arithmetic operators are often encountered in early mathematics and include addition(+), subtraction (-), multiplication (), division (/), and modulus (%). They also include theunary operators, ++ and –, although we cover them later in this chapter. As you may havenoticed above, the multiplicative operators (, /, %) have a higher order of precedencethan the additive operators (+, -). That means when you see an expression such as this:

int x = 2 * 5 + 3 * 4 - 8;

you first evaluate the 2 * 5 and 3 * 4, which reduces the expression to the following:

int x = 10 + 12 - 8;

Then, you evaluate the remaining terms in left-to-right order, resulting in a value of x of14. Make sure you understand why the result is 24 as youll likely see this kind of operatorprecedence question on the exam

Note :The modulus operation is not limited to positive integer values in Javaand may also be applied to negative integers and floating-point integers.For a given divisor y and negative dividend, the resulting modulus valueis between and (-y + 1) and 0. For the OCA exam, though, you are notrequired to be able to take the modulus of a negative integer or a floating pointnumber.

Working with Unary Operators

By definition, a unary operator is one that requires exactly one operand, or variable, tofunction. As shown below, they often perform simple tasks, such as increasing anumeric variable by one, or negating a boolean value.

Java Unary Operator

The logical complement operator, !, flips the value of a boolean expression. For example,if the value is true, it will be converted to false, and vice versa. To illustrate this, comparethe outputs of the following statements:

boolean x = false;
System.out.println(x); // false
x = !x;
System.out.println(x); // true

Additional examples

//Likewise, the negation operator, -, reverses the sign of a numeric expression, as shown in these statements:
double x = 1.21;
System.out.println(x); // 1.21
x = -x;
System.out.println(x); // -1.21
x = -x;
System.out.println(x); // 1.21
int x = !5; // DOES NOT COMPILE
boolean y = -true; // DOES NOT COMPILE
boolean z = !0; // DOES NOT COMPILE

Note:Keep an eye out for questions on the exam that use the logical complementoperator or numeric values with boolean expressions or variables. Unlikesome other programming languages, in Java 1 and true are not related inany way, just as 0 and false are not related.

Increment and decrement operators, ++ and –, respectively, can be applied to numericoperands and have the higher order or precedence, as compared to binary operators. Inother words, they often get applied first to an expression.

//The following code snippet illustrates this distinction:
int counter = 0;
System.out.println(counter); // Outputs 0
System.out.println(++counter); // Outputs 1
System.out.println(counter); // Outputs 1
System.out.println(counter--); // Outputs 1
System.out.println(counter); // Outputs 0

One common practice in a certifi cation exam, albeit less common in the real world, is toapply multiple increment or decrement operators to a single variable on the same line:

int x = 3;
int y = ++x * 5 / x-- + --x;
System.out.println("x is " + x);
System.out.println("y is " + y);

Using Additional Binary Operators

An assignment operator is a binary operator that modifies, or assigns, the variable onthe left-hand side of the operator, with the result of the value on the right-hand side ofthe equation. The simplest assignment operator is the = assignment, which you have seen already:

int x = 1;

This statement assigns x the value of 1. Java will automatically promote from smaller to larger data types, as we saw in the previoussection on arithmetic operators, but it will throw a compiler exception if it detectsyou are trying to convert from larger to smaller data types.Lets return to some examples similar to what you saw in Chapter 1 in order to showhow casting can resolve these issues:

int x = 1.0; // DOES NOT COMPILE
short y = 1921222; // DOES NOT COMPILE
int z = 9f; // DOES NOT COMPILE
long t = 192301398193810323; // DOES NOT COMPILE

Casting Primitive Values We can fix the examples in the previous section by casting the results to a smaller data type. Casting primitives is required any time you are going from a larger numerical datatype to a smaller numerical data type, or converting from a fl oating-point number to an integral value.

int x = (int)1.0;
short y = (short)1921222; // Stored as 20678
int z = (int)9l;
long t = 192301398193810323L;

Compound Assignment Operators Besides the simple assignment operator, =, there are also numerous compound assignmentoperators. Only two of the compound operators listed above are required for theexam, += and -=. Complex operators are really just glorified forms of the simple assignmentoperator, with a built-in arithmetic or logical operation that applies the left- and right-handsides of the statement and stores the resulting value in a variable in the left-hand side of thestatement. For example, the following two statements after the declaration of x and z areequivalent:

int x = 2, z = 3;
x = x * z; // Simple assignment operator
x *= z; // Compound assignment operator

Relational Operators We now move on to relational operators, which compare two expressions and return aboolean value. The first four relational operators (see below picture) are applied to numericprimitive data types only. If the two numeric operands are not of the same data type, thesmaller one is promoted in the manner as previously discussed.


//Lets look at examples of these operators in action:
int x = 10, y = 20, z = 10;
System.out.println(x  y); // Outputs true
System.out.println(x = y); // Outputs true
System.out.println(x = z); // Outputs true
System.out.println(x  z); // Outputs false

Understanding Java Statements

Java operators allow you to create a lot of complex expressions, but theyre limited in themanner in which they can control program flow. For example, imagine you want a sectionof code to only be executed under certain conditions that cannot be evaluated untilruntime. Or suppose you want a particular segment of code to repeat once for every item insome list.

The if-then Statement Often, we only want to execute a block of code under certain circumstances. The if-thenstatement, executea particular block of code if and only if a boolean expression evaluates to true at runtime.

The if-then-else Statement Lets expand our example a little. What if we want to display a different message if it is 11a.m. or later? Could we do it using only the tools we have? Of course we can!

if(hourOfDay  11) {
System.out.println("Good Morning");
} else {
System.out.println("Good Afternoon");

Ternary Operator Now that we have discussed if-then-else statements, we can briefly return to our discussionof operators and present the fi nal operator that you need to learn for the exam. Theconditional operator, ? :, otherwise known as the ternary operator, is the only operatorthat takes three operands and is of the form: booleanExpression ? expression1 : expression2 The fi rst operand must be a boolean expression, and the second and third can be anyexpression that returns a value. The ternary operation is really a condensed form of an if-then-else statement that returns a value. For example, the following two snippets of code are equivalent:

int y = 10;
final int x;
if(y  5) {
x = 2 * y;
} else {
x = 3 * y;

Compare the previous code snippet with the following equivalent ternary operator codesnippet:

int y = 10;
int x = (y  5) ? (2 * y) : (3 * y);

The switch Statement We now expand on our discussion of if-then-else statements by discussing a switchstatement. A switch statement, as shown earlier, is a complex decision-making structurein which a single value is evaluated and fl ow is redirected to the first matching branch, known as a case statement. Lets look at a simple example using the day of the week, with 0 for Sunday, 1 forMonday, and so on:

int dayOfWeek = 5;
switch(dayOfWeek) {
case 0:
case 6:

The while Statement A repetition control structure, which we refer to as a loop, executes a statement of codemultiple times in succession. By using non constant variables, each repetition of the statementmay be different. For example, a statement that iterates over a list of unique namesand outputs them would encounter a new name on every execution of the loop.

The do-while Statement Java also allows for the creation of a do-while loop, which like a while loop, is a repetition control structure with a termination condition and statement, or block ofstatements. Unlike a while loop, though, a do-while loop guarantees that the statement or block will be executed at least once.The primary difference between the syntactic structure of a do-while loop and a whileloop is that a do-while loop purposely orders the statement or block of statements beforethe conditional expression, in order to reinforce that the statement will be executed beforethe expression is ever evaluated. For example, take a look at the output of the followingstatements:

int x = 0;
do {
} while(false);
System.out.println(x); // Outputs 1

The for Statement Now that you can build applications with simple while and do-while statements, weexpand our discussion of loops to a more complex repetition control structure called a forloop. Starting in Java 5.0, there are now two types of for statements. The fi rst is referred to asthe basic for loop, and the second is often called the enhanced for loop. For clarity, wellrefer to the enhanced for loop as the for-each statement throughout the book. The Basic for Statement A basic for loop has the same conditional boolean expression and statement, or block ofstatements, as the other loops you have seen, as well as two new sections: an initializationblock and an update statement. Below snippet shows how these components are laid out.

for(int i = 0; i  10; i++) {
System.out.print(i + " ");

Adding Multiple Terms to the for Statement

int x = 0;
for(long y = 0, z = 4; x  5 && y  10; x++, y++) {
System.out.print(y + " ");

This code demonstrates three variations of the for loop you may not have seen. First, youcan declare a variable, such as x in this example, before the loop begins and use it after itcompletes. Second, your initialization block, boolean expression, and update statementscan include extra variables that may not reference each other. For example, z is defined inthe initialization block and is never used. Finally, the update statement can modify multiplevariables.

The for-each Statement Starting with Java 5.0, Java developers have had a new type of enhanced for loop at theirdisposal, one specifi cally designed for iterating over arrays and Collection objects. Thisenhanced for loop, which for clarity well refer to as a for-each loop.

final String[] names = new String[3];
names[0] = "Lisa";
names[1] = "Kevin";
names[2] = "Roger";
for(String name : names) {
System.out.print(name + ", ");

Understanding Advanced Flow Control

Up to now, we have been dealing with single loops that only ended when their booleanexpression evaluated to false. Well now show you other ways loops could end, or branch,and youll see that the path taken during runtime may not be as straightforward as in previousexamples.

Nested Loops First off, loops can contain other loops. For example, consider the following code that iteratesover a two-dimensional array, an array that contains other arrays as its members. Wellcover multidimensional arrays in detail in Chapter 3, but for now assume the following ishow you would declare a two-dimensional array.

for(int[] mySimpleArray : myComplexArray) {
for(int i=0; imySimpleArray.length; i++) {

Notice that we intentionally mix a for and for-each loop in this example. The outerloops will execute a total of three times. Each time the outer loop executes, the inner loopis executed four times. When we execute this code, we see the following output: 5 2 1 3 3 9 8 9 5 7 12 7 Nested loops can include while and do-while, as shown in this example. See if you candetermine what this code will output.

int x = 20;
while(x0) {
do {
x -= 2
} while (x5);

Adding Optional Labels One thing we skipped when we presented if-then statements, switch statements, andloops is that they can all have optional labels. A label is an optional pointer to the head of astatement that allows the application fl ow to jump to it or break from it. It is a single word that is proceeded by a colon (:). For example, we can add optional labels to one of the previousexamples:

OUTER_LOOP: for(int[] mySimpleArray : myComplexArray) {
INNER_LOOP: for(int i=0; imySimpleArray.length; i++) {

The break Statement As you saw when working with switch statements, a break statement transfers the flowof control out to the enclosing statement. The same holds true for break statements thatappear inside of while, do-while, and for loops, as it will end the loop early.

public class SearchSample {
public static void main(String[] args) {

int searchValue = 2;
int positionX = -1;
int positionY = -1;
PARENT_LOOP: for(int i=0; ilist.length; i++) {
for(int j=0; jlist[i].length; j++) {
if(list[i][j]==searchValue) {
positionX = i;
positionY = j;
if(positionX==-1 || positionY==-1) {
System.out.println("Value "+searchValue+" not found");
} else {
System.out.println("Value "+searchValue+" found at: " +

The continue Statement Lets now complete our discussion of advanced loop control with the continue statement, astatement that causes flow to finish the execution of the current loop

public class SwitchSample {
public static void main(String[] args) {
FIRST_CHAR_LOOP: for (int a = 1; a = 4; a++) {
for (char x = 'a'; x = 'c'; x++) {
if (a == 2 || x == 'b')
System.out.print(" " + a + x);

Exam Essentials Be able to write code that uses Java operators. This article covered a wide variety ofoperator symbols. Go back and review them several times so that you are familiar withthem.Be able to recognize which operators are associated with which data types. Some operatorsmay be applied only to numeric primitives, some only to boolean values, and someonly to objects. It is important that you notice when an operator and operand(s) are mismatched,as this issue is likely to come up in a couple of exam questions.

All OCJP Java Certification Tutorials

  1. Oracle (OCJP) Java Certification Exam
  2. Java Building Blocks Java 8 Certification
  3. Operators And Statements
  4. Java Core API
  5. Java Class Design
  6. Java Exception
  7. Java Try-Catch Block
  8. Exceptional Handling in Java
  9. Common Exception in Java