Java Lesson 5: Operators and Expressions

0
22

Introduction

In mathematics an expression is of the form y = 2x + 8. In Java, an expression is quite similar. It is a properly formed sequence of variables, constants, methods, special symbols, and operators. In this tutorial we will see how operators and expressions are used to solve complex problems in Java.

Java has several operator groups. We will cover the most common groups: Arithmetic, Relational, Boolean Logical, and Assignment. Other groups include Bitwise and Ternary (?) operators. There are a few differences, but most operators will be familiar if you have experience with another programming language. Many are derived from common mathematical operations.

Arithmetic Operators

The Java Arithmetic operators perform common math operations, and are shown in the following table.

Operator  Operation Example
 + Addition x + y
Subtraction x – y
* Multiplication x * y
/ Division x / y
% Modulus x % y
++ Increment x++
Decrement x- –
+= Addition Assignment x += y
-= Subtraction Assignment x -= y
*= Multiplication Assignment x *= y
/= Division Assignment x /= y
%= Modulus Assignment x %= y

The modulus operator, “%“, returns the remainder of a division; for example, 3 / 2 = 1, with a remainder of 1.

The increment operator, “++“, automatically adds 1 and stores the result into the original variable. The statement “x++;” is equivalent to “x = x + 1;“. It is commonly used in for loops and indexing arrays.

The decrement operator, “--“, automatically subtracts 1 and stores the result into the original variable. The statement “x--;” is equivalent to “x = x – 1;“. It is commonly used in for loops which count down (eg. counting down from 10 to 1) as the following program does.

The Addition, Subtraction, Multiplication, and Modulus Assignment statements may look odd at first, but they are really just a shorthand way of using the more familiar statements. For example, the following two statements are equivalent, but the second one requires less typing.

Relational Operators

The Java Relational operators compare two values for equality or ordering, and are shown in the following table.

Operator  Operation Example
 == Equal to  if (n == 10) {
!= Not equal to  if (n != 10) {
> Greater than  if (n > 10) {
< Less than  if (n < 10) {
>= Greater than or equal to  if (n >= 10) {
<= Less than or equal to  if (n <= 10) {

These operations always return a boolean value, and are most frequently used in expressions that control the if statement or Java’s looping statements such as while and for. The following code fragments demonstrate how they are used.

Boolean Logical

The Java Boolean Logical operators operate only on boolean operands. They all combine two boolean values to form a resultant boolean value. The operators are shown in the following table.

Operator  Operation Example
! Logical unary NOT if (!done) {
& Logical AND if ( (a < 5) & (b > 10) ) {
| Logical OR if ( (a < 5) | (b > 10) ) {
&& Short-circuit AND if ( (a < 5) && (b > 10) ) {
|| Short-circuit OR if ( (a < 5) || (b > 10) ) {
== Equal to if (a == 5) {

The Boolean Logical operators are often described in a Truth Table. A Truth Table works similar to a multiplication table – select values for A and B, then go across the table to the appropriate column, and read the resultant value. For example, if A is true and B is false, then A & B is false. Similarly, if A is true, then !A (ie., NOT A) returns false because the opposite of true is false.

B  A & B A | B !A
true true true true false
true false false true false
false true false true true
false false false false true

The & and | operators evaluate both sides of the argument before deciding on the result. The && and || operators are called short-circuit operators because they avoid the evaluation of right-hand operands if it need not be performed. For example, in the snippet below if the value of cost is greater than $9.99 , then the Java VM will not need to evaluate the right side of the expression (ie. is InInventory == true) because the condition has already been satisfied. This saves a little bit of computer processing time.

It is common practice to use the short-circuit forms in cases involving Boolean logic.

Assignment Operator

Java has only one Assignment operator: the equal sign.

Operator  Operation Example
 = Assigns to  area = width * height;

Expressions

We briefly touched on expressions in Tutorial 2, and will now discuss them in detail.

Expressions will be evaluated according to the rules of precedence, where all operations of higher precedence are performed before those of lower precedence. Operations contained within parenthesis are performed first, and if necessary parenthesis can be nested to ensure the proper order or for clarity. Operations of equal precedence are performed from left to right.

The order of precedence is:

  • inside parenthesis
  • multiplication, division
  • addition, subtraction

As an example, consider:

(6.0 * Math.cos(45.0)) + x * y – a / d

The compiler scans the expression from left to right, looking for the highest precedence operator. It then determines a value for Math.cos(pi) and multiplies it by 6. The intermediate result is 3.15. The expression is scanned again from left to right. Values for x * y and a / d are determined on this scan. Finally, it is scanned again from left to right, and the addition and subtraction operations are performed.

We can write and run a Java program that performs operations on the above expression.

tutorial5_1

You can use a calculator to confirm this result; just be sure to use radians instead of degrees when performing the cos() operation.

Consider the expression:

Java evaluates this as:

rather than as:

You can use parenthesis to ensure the proper order or for clarity depending upon what you want to do.

(x / y) + z
x / (y + z)

An expression may also be a String or string variable.

Examples of Using Operators and Expressions in Java

Here is a variety of examples of valid Java statements which use operators and expressions.

An example of a fairly long and complex expression that you can enter and run is in the Java Snippet Evaluate a Polynomial.

Summary

In this tutorial we learned how operators are used to create complex expressions to do useful work such as mathematical calculations and String manipulation.

Next Lesson

Next we will move on to Simple Console Input/Output which will enable us to enter values for variables at runtime and to display the results on the user’s screen.

 

Leave a Reply