Operators and Statements Java 8 Certification

Operators and Statements is 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 Statement fundamental. 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, or literals—referred to as operands—and that returns a result. Three flavors of operators are available in Java: unary, binary, and ternary. These types of operators can be applied to
one, two, or three operands, respectively. For the OCA exam, you’ll 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 operators involved:

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

In this example, you would first decrementy to 3, and then multiply the resulting value by 2, and finally add 3. The value would then be automatically upcast from 9 to 9.0 and assigned to x. The final values of x and y would be 9.0 and 3, respectively. If you didn’t
follow that evaluation, don’t worry. By the end of this chapter, solving problems like this should 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 Arithmetic Operators

Binary operators are 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 the unary operators, ++ and –, although we cover them later in this chapter. As you may have noticed above, the multiplicative operators (*, /, %) have a higher order of precedence than 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 of 14. Make sure you understand why the result is 24 as you’ll likely see this kind of operator precedence question on the exam

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

Working with Unary Operators

By definition, a unary operator is one that requires exactly one operand, or variable, to function. As shown below, they often perform simple tasks, such as increasing a numeric 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, compare the 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 complement operator or numeric values with boolean expressions or variables. Unlike some other programming languages, in Java 1 and true are not related in any way, just as 0 and false are not related.

Increment and decrement operators, ++ and –, respectively, can be applied to numeric operands and have the higher order or precedence, as compared to binary operators. In other 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 to apply 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 on the left-hand side of the operator, with the result of the value on the right-hand side of the 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 previous section on arithmetic operators, but it will throw a compiler exception if it detects you are trying to convert from larger to smaller data types. Let’s return to some examples similar to what you saw in Chapter 1 in order to show how 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 data type 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 assignment operators. Only two of the compound operators listed above are required for the exam, += and -=. Complex operators are really just glorified forms of the simple assignment operator, with a built-in arithmetic or logical operation that applies the left- and right-hand sides of the statement and stores the resulting value in a variable in the left-hand side of the statement. For example, the following two statements after the declaration of x and z are equivalent:

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 a boolean value. The first four relational operators (see below picture) are applied to numeric primitive data types only. If the two numeric operands are not of the same data type, the smaller one is promoted in the manner as previously discussed.

relational-operator

//Let’s 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 they’re limited in the manner in which they can control program flow. For example, imagine you want a section of code to only be executed under certain conditions that cannot be evaluated until runtime. Or suppose you want a particular segment of code to repeat once for every item in some list.

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

The if-then-else Statement
Let’s expand our example a little. What if we want to display a different message if it is 11 a.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 discussion of operators and present the fi nal operator that you need to learn for the exam. The conditional operator, ? :, otherwise known as the ternary operator, is the only operator that 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 any expression 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 code snippet:

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 switch statement. A switch statement, as shown earlier, is a complex decision-making structure in which a single value is evaluated and fl ow is redirected to the first matching branch,
known as a case statement.

Let’s look at a simple example using the day of the week, with 0 for Sunday, 1 for Monday, and so on:

int dayOfWeek = 5;
switch(dayOfWeek) {
default:
System.out.println("Weekday");
break;
case 0:
System.out.println("Sunday");
break;
case 6:
System.out.println("Saturday");
break;
}

The while Statement
A repetition control structure, which we refer to as a loop, executes a statement of code multiple times in succession. By using non constant variables, each repetition of the statement may be different. For example, a statement that iterates over a list of unique names and 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 of statements. 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 while loop is that a do-while loop purposely orders the statement or block of statements before the conditional expression, in order to reinforce that the statement will be executed before the expression is ever evaluated. For example, take a look at the output of the following statements:

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

The for Statement
Now that you can build applications with simple while and do-while statements, we expand our discussion of loops to a more complex repetition control structure called a for loop.
Starting in Java 5.0, there are now two types of for statements. The fi rst is referred to as the basic for loop, and the second is often called the enhanced for loop. For clarity, we’ll refer 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 of statements, as the other loops you have seen, as well as two new sections: an initialization block 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 + " ");
}
System.out.print(x);

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

The for-each Statement
Starting with Java 5.0, Java developers have had a new type of enhanced for loop at their disposal, one specifi cally designed for iterating over arrays and Collection objects. This enhanced for loop, which for clarity we’ll 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 boolean expression evaluated to false. We’ll now show you other ways loops could end, or branch, and you’ll see that the path taken during runtime may not be as straightforward as in previous examples.

Nested Loops
First off, loops can contain other loops. For example, consider the following code that iterates over a two-dimensional array, an array that contains other arrays as its members. We’ll cover multidimensional arrays in detail in Chapter 3, but for now assume the following is how you would declare a two-dimensional array.

int[][] myComplexArray = {{5,2,1,3},{3,9,8,9},{5,7,12,7}};
for(int[] mySimpleArray : myComplexArray) {
for(int i=0; i<mySimpleArray.length; i++) {
System.out.print(mySimpleArray[i]+"\t");
}
System.out.println();
}

Notice that we intentionally mix a for and for-each loop in this example. The outer loops will execute a total of three times. Each time the outer loop executes, the inner loop is 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 can determine what this code will output.

int x = 20;
while(x>0) {
do {
x -= 2
} while (x>5);
x--;
System.out.print(x+"\t");
}

Adding Optional Labels
One thing we skipped when we presented if-then statements, switch statements, and loops is that they can all have optional labels. A label is an optional pointer to the head of a statement 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 previous examples:

int[][] myComplexArray = {{5,2,1,3},{3,9,8,9},{5,7,12,7}};
OUTER_LOOP: for(int[] mySimpleArray : myComplexArray) {
INNER_LOOP: for(int i=0; i<mySimpleArray.length; i++) {
System.out.print(mySimpleArray[i]+"\t");
}
System.out.println();
}

The break Statement
As you saw when working with switch statements, a break statement transfers the flow of control out to the enclosing statement. The same holds true for break statements that appear 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[][] list = {{1,13,5},{1,2,5},{2,7,2}};
int searchValue = 2;
int positionX = -1;
int positionY = -1;
PARENT_LOOP: for(int i=0; i<list.length; i++) {
for(int j=0; j<list[i].length; j++) {
if(list[i][j]==searchValue) {
positionX = i;
positionY = j;
break PARENT_LOOP;
}
}
}
if(positionX==-1 || positionY==-1) {
System.out.println("Value "+searchValue+" not found");
} else {
System.out.println("Value "+searchValue+" found at: " +
"("+positionX+","+positionY+")");
}
}
}

The continue Statement
Let’s now complete our discussion of advanced loop control with the continue statement, a statement 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')
continue FIRST_CHAR_LOOP;
System.out.print(" " + a + x);
}
}
}
}

Exam Essentials
Be able to write code that uses Java operators. This article covered a wide variety of operator symbols. Go back and review them several times so that you are familiar with them. Be able to recognize which operators are associated with which data types. Some operators may be applied only to numeric primitives, some only to boolean values, and some only 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.

 

Comments are closed.