2

Performing operations

This chapter demonstrates the various operators that are used to create expressions in Java programs.

Doing arithmetic

Assigning values

Comparing values

Assessing logic

Examining conditions

Setting precedence

Escaping literals

Working with bits

Summary

Doing arithmetic

Arithmetical operators, listed in the table below, are used to create expressions in Java programs that return a single resulting value. For example, the expression 4 * 2 returns the value 8.

Operator:

Operation:

+

Addition (and concatenates String values)

-

Subtraction

*

Multiplication

/

Division

%

Modulus

++

Increment

--

Decrement

image

Division of int values will truncate any fractional part. For example, 11/4 = 2, whereas division of float values 11/4 = 2.75.

The increment operator ++ and decrement operator -- return the result of modifying a single given operand by a value of one. For example, 4++ returns the value 5, and 4-- returns the value 3.

All other arithmetic operators return the result of an operation performed on two given operands, and act as you would expect. For example, the expression 5 + 2 returns 7.

The modulus operator divides the first operand by the second operand and returns the remainder of the operation. For example, 32 % 5 returns 2 – five divides into 32 six times, with 2 remainder.

The operation performed by the addition operator + depends on the type of its given operands. Where both operands are numeric values it will return the total sum value of those numbers, but where the operands are String values it will return a single concatenated String – combining the text in each String operand. For example, “Java ” + “Arithmetic” returns “Java Arithmetic”.

image

Increment and decrement operators are typically used to count the iterations in the for loop constructs, introduced here .

Follow these steps to explore the Java arithmetic operators in the Java shell:

imageOpen a command-line prompt window, then type jshell and hit the Enter key to launch the Java shell

imageNext, enter statements to initialize three variables

int num = 100 ; int factor = 20 ; int sum = 0 ;

image

imageNext, separately enter statements to perform addition and subtraction operations, displaying each result

sum = num + factor ;

sum = num - factor ;

image

imageNow, separately enter statements to perform multiplication and division operations, displaying each result

sum = num * factor ;

sum = num / factor ;

image

image

Java must be installed on your system path to launch the Java shell from any prompt – see Installing here and Troubleshooting here for details.

image

The Java shell jshell is a new feature in Java 9. Optionally, the semicolon character may be omitted at the end of single statements entered into the shell but these are required when writing Java programs for compilation. Semicolons are included in the shell examples in this chapter to aid code consistency.

Assigning values

Assignment operators, listed in the table below, are used to assign the result of an expression. All except the simple = operator are the shorthand form of a longer equivalent expression:

Operator:

Example:

Equivalent:

=

a = b

a = b

+=

a += b

a = a + b

-=

a -= b

a = a - b

*=

a *= b

a = a * b

/=

a /= b

a = a / b

%=

a %= b

a = a % b

It is important to regard the = operator to mean “assign”, rather than “equals”, to avoid confusion with the == equality operator.

In the example a = b, the value stored in the variable named b is assigned to the variable named a, so that value becomes the new value stored in a – replacing any value it previously contained.

The += operator is useful to add a value onto an existing value stored in a variable – keeping a “running total”.

The example a += b first calculates the sum total of the values stored in the variables named a and b, then assigns the resulting total to variable a. A program might then contain a further assignment a += c that calculates the total stored in variables named a and c, then assigns that new total to variable a – adding the value of c to the value it previously contained.

All the other assignment operators work in the same way by first performing the arithmetical calculation on the two stored values, then assigning the result to the first variable – to become its new stored value.

image

The == equality operator compares values, and is fully explained here .

Follow these steps to explore the Java assignment operators in the Java shell:

imageOpen a command-line prompt window, then type jshell and hit the Enter key to launch the Java shell

imageNext, enter statements to initialize two String variables

String txt = “Super ” ; String lang = “Java” ;

imageNow, separately enter statements to add and assign a String value, then display the concatenated string result

txt += lang ; txt ;

image

imageThen, enter statements to initialize two integer variables

int sum = 10 ; int num = 20 ;

imageSeparately enter statements to add and assign an int value, then display the totaled integer result

sum += num ; sum ;

image

image

The new Java shell feature, introduced in Java 9, creates internal $-prefixed numbered variables containing the result of an evaluation. Here, internal variables $3 and $7 contain evaluation results.

image

Assignment of the wrong data type to a variable will cause an error.

Comparing values

Comparison operators, listed in the table below, are used to compare two values in an expression and return a single Boolean value of true or false – describing the result of that comparison.

Operator:

Comparison:

==

Equality

!=

Inequality

>

Greater than

>=

Greater than, or equal to

<

Less than

<=

Less than, or equal to

The == equality operator compares two operands, and will return true if both are exactly equal in value. If both are the same number they are equal, or if both are String values containing the same characters in the same order they are equal. Boolean operands that are both true, or that are both false, are equal.

Conversely, the != inequality operator returns true if two operands are not equal – applying the same rules as the equality operator.

Equality and inequality operators are useful in testing the state of two variables to perform “conditional branching” of a program – proceeding in different directions according to the condition.

The > “greater than” operator compares two operands, and will return true if the first is greater in value than the second.

The < “less than” operator makes the same comparison, but returns true if the first operand is less in value than the second.

Adding the = assignment operator after the > “greater than” operator, or after the < “less than” operator, makes it also return true when the two operands are exactly equal in value.

image

The < less than operator is typically used to test a counter value in a loop – an example of this can be found here .

Follow these steps to explore the Java comparison operators in the Java shell:

imageOpen a command-line prompt window, then type jshell and hit the Enter key to launch the Java shell

imageNext, enter statements to initialize two String variables

String txt = “Super ” ; String lang = “Java” ;

imageNow, separately enter statements to initialize a boolean variable and display the result of String value comparisons for equality and inequality

boolean state = ( txt == lang ) ;

state = ( txt != lang ) ;

image

imageIn a similar way, separately enter these statements to display the result of int value comparisons for greater and less numeric value

int dozen = 12 ; int score = 20 ;

state = ( dozen > score ) ;

state = ( dozen < score ) ;

image

image

You can discover more options within the Java shell by entering the /help command.

image

Here it’s untrue (false) that the String values are equal, but it is true that they are unequal.

image

Notice how an expression can be contained in parentheses for better readability.

Assessing logic

Logical operators, listed in the table below, are used to combine multiple expressions that each return a Boolean value – into a complex expression that returns a single Boolean value.

Operator:

Operation:

&&

Logical AND

||

Logical OR

!

Logical NOT

Logical operators are used with operands that have the Boolean values of true or false, or values that can convert to true or false.

The logical && AND operator will evaluate two operands and return true only if both operands are themselves true. Otherwise, the logical && operator will return false. This evaluation can be used in conditional branching, where a program will only perform a certain action when two tested conditions are both true.

Unlike the logical && operator that needs two operands to be true, the logical || OR operator will evaluate its two operands and return true if either one of the operands is true – it will only return false when neither operand is true. This is useful in Java programming to perform a certain action when either one of two test conditions has been met.

The logical ! NOT operator is a “unary” operator that is used before a single operand. It returns the inverse Boolean value of the given operand – reversing true to false, and false to true. It’s useful in Java programs to toggle the value of a variable in successive loop iterations with a statement like goState=!goState. This ensures that on each pass of the loop the value is changed, like flicking a light switch on and off.

image

The term “Boolean” refers to a system of logical thought developed by the English mathematician George Boole (1815-1864).

image

image

The new Java shell feature, introduced in Java 9, is also known as a “REPL” – an acronym for Read, Evaluate, Print, Loop that describes this type of interactive tool.

Follow these steps to explore logical operators in the Java shell:

imageOpen a command-line prompt window, then type jshell and hit the Enter key to launch the Java shell

imageNext, enter statements to initialize two boolean variables

boolean yes = true ; boolean no = false ;

imageEnter statements to test if both two conditions are true

boolean result = ( yes && yes ) ; result = ( yes && no ) ;

image

imageEnter statements to test if either of two conditions is true

result = ( yes || yes ) ;

result = ( yes || no ) ;

result = ( no || no ) ;

imageEnter statements to show an original and inverse value

result = yes ; result = !yes ;

image

image

Notice that false && false returns false, not true – demonstrating the maxim that “two wrongs don’t make a right”.

image

The value returned by the ! NOT logical operator is the inverse of the stored value – the stored value itself remains unchanged.

Examining conditions

Possibly the all-time favorite operator of the Java programmer is the ? : conditional operator that makes a powerful statement very concisely. Its unusual syntax can seem tricky to understand at first, but it is well worth getting to know this useful operator.

The conditional operator first evaluates an expression for a true or false value, then returns one of two given operands depending on the result of the evaluation. Its syntax looks like this:

( boolean-expression ) ? if-true-return-this : if-false-return-this ;

image

The conditional operator is also known as the “ternary” operator.

Each specified operand alternative allows the program to progress according to the Boolean value returned by the tested expression. For instance, the alternatives might return a String value:

status = ( quit == true ) ? “Done!” : “Continuing...” ;

In this case, when the quit variable is true the conditional operator assigns the value of its first operand to the status variable; otherwise, it assigns its second operand value instead.

A shorthand available when coding Java programs allows expressions to optionally omit == true when evaluating a simple Boolean value, so the example above can be written simply as:

status = ( quit ) ? “Done!” : “Continuing...” ;

The conditional operator can return values of any data type and employ any valid test expression. For instance, the expression might use the greater than > operator to evaluate two numeric values then return a Boolean value depending on the result:

busted = ( speed > speedLimit ) ? true : false ;

Similarly, the conditional operator might employ the inequality != operator to evaluate a String value then return a numeric value depending on the result:

bodyTemperature = ( scale != “Celsius” ) ? 98.6 : 37.0 ;

image

You can also start the Java shell with the command jshell--feedback verbose to receive descriptive output after each evaluation.

Follow these steps to explore the Java conditional operator in the Java shell:

imageOpen a command-line prompt window, then type jshell and hit the Enter key to launch the Java shell

imageNext, enter statements to initialize two int variables

int num1 = 1357 ; int num2 = 2468 ;

imageDeclare a further variable to store a test result String

String result ;

imageEnter this statement to determine whether the first integer value is an odd or even number

result = ( num1 % 2 != 0 ) ? “Odd” : “Even” ;

image

imageNow, enter this statement to determine whether the second integer value is an odd or even number

result = ( num2 % 2 != 0 ) ? “Odd” : “Even” ;

image

image

Notice that an uninitialized String variable returns a special null value – indicating that it contains nothing whatsoever.

image

Here, the expression evaluates as true when there is any remainder.

Setting precedence

Complex expressions, which contain multiple operators and operands, can be ambiguous unless the order in which the operations should be executed is clear. This lack of clarity can easily cause different results to be implied by the same expression. For example, consider this complex expression:

num = 8 + 4 * 2 ;

Working left to right 8 + 4 = 12, and 12 * 2 = 24, so num = 24. But working right to left 2 * 4 = 8, and 8 + 8 = 16, so num = 16.

The Java programmer can explicitly specify which operation should be executed first by adding parentheses to signify which operator has precedence. In this case, (8 + 4) * 2 ensures that the addition is performed before the multiplication – so the result is 24, not 16. Conversely, 8 + (4 * 2) performs the multiplication first – so the result is 16, not 24.

Where parentheses do not explicitly specify operator precedence Java follows the default precedence order listed in the table below, from first at the top to last at the bottom:

Operator:

Description:

++ -- !

Increment, Decrement, Logical NOT

* / %

Multiplication, Division, Modulus

+ -

Addition, Subtraction

> >=< <=

Greater than, Greater than or equal toLess than, Less than or equal to

== !=

Equality, Inequality

&&

Logical AND

||

Logical OR

? :

Conditional

= += -= *= /= %=

Assignment

image

Operators of equal precedence are handled in the order they appear in the expression – from left to right.

Follow these steps to explore operator precedence in the Java shell:

imageOpen a command-line prompt window, then type jshell and hit the Enter key to launch the Java shell

imageNext, enter a statement to display the result of evaluating an expression that uses default operator precedence

int sum = 32 - 8 + 16 * 2 ;

image

imageNow, enter a statement to display the result of evaluating the same expression – but giving addition and subtraction precedence over multiplication

sum = ( 32 - 8 + 16 ) * 2 ;

image

imageFinally, enter a statement to display the result of evaluating the same expression once more – but now where operation precedence order is first addition, then subtraction, and then multiplication

sum = ( 32 - ( 8 + 16 ) ) * 2 ;

image

image

Where expressions have multiple nested parentheses, the innermost takes precedence.

image

How it works – Step 2 ...

16 x 2 = 32, + 24 = 56

Step 3...

24 + 16 = 40, x 2 = 80

Step 4 ...

32 - 24 = 8, x 2 = 16

image

This chapter has so far used the Java shell jshell to explore the various Java operators by evaluating code snippets. Ensuing examples will use the Java compiler javac and Java runtime java to create and execute programs. You can quit the Java shell to return to a regular prompt with the command /exit.

Escaping literals

The numerical and text values in Java programs are known as “literals” – they represent nothing but are, literally, what you see.

Literals are normally detached from the keywords of the Java language, but where double quotes, or single quotes, are required within a String value it is necessary to indicate that the quote character is to be treated literally to avoid prematurely terminating the String. This is easily achieved by immediately prefixing each nested quote character with the \ escape operator. For example, including a quote within a String variable, like this:

String quote = “ \”Fortune favors the brave.\” said Virgil ”;

Additionally, the \ escape operator offers a variety of useful escape sequences for simple output formatting:

Escape:

Description:

\n

Newline

\t

Tab

\b

Backspace

\r

Carriage return

\f

Formfeed

\\

Backslash

\’

Single quote mark

\”

Double quote mark

image

Single quotes can be nested within double quotes as an alternative to escaping quote characters.

The \n newline escape sequence is frequently used within long String values to display the output on multiple lines. Similarly, the \t tab escape sequence is frequently used to display the output in columns. Using a combination of \n newline and \t tab escape sequences allows the output to be formatted in both rows and columns – to resemble a table.

Follow these steps to create a Java program using escape sequences to format the output:

imageStart a new program named “Escape” containing the standard main method

class Escape

{

public static void main( String[] args ) {         }

}

image

Escape.java

imageBetween the curly brackets of the main method, insert this code to build a String containing a formatted table title and column headings

String header = “\n\tNEW YORK 3-DAY FORECAST:\n” ;

header += “\n\tDay\t\tHigh\tLow\tConditions\n” ;

header += “\t---\t\t----\t---\t----------\n” ;

imageAdd these lines to build a String containing formatted table cell data

String forecast = “\tSunday\t\t68F\t48F\tSunny\n” ;

forecast += “\tMonday\t\t69F\t57F\tSunny\n” ;

forecast += “\tTuesday\t\t71F\t50F\tCloudy\n” ;

imageNow, add this line to output both formatted String values

System.out.print( header + forecast ) ;

imageSave the program as Escape.java, then compile and run the program

image

image

In this case, escape sequences add newlines so the print() method is used here – rather than the println() method that automatically adds a newline after output.

Working with bits

In addition to the regular operators described earlier in this chapter, Java provides special operators for binary arithmetic. These are less commonly used than other operators, but are briefly discussed here to simply provide an awareness of their existence.

The Java “bitwise” operators can be used with the int integer data type to manipulate the bits of the binary representation of a value. This requires an understanding of binary numbering, where eight bits in a byte represent decimal values zero to 255. For example,

53 is binary 00110101

(0 x 128, 0 x 64, 1 x 32, 1 x 16, 0 x 8, 1 x 4, 0 x 2, 1 x 1).

Binary addition operations are performed like decimal arithmetic:

 

53

=

00110101

+

7

=

00000111

 

60

=

00111100

The bitwise operators, listed below, allow more specialized operations to be performed in binary arithmetic.

Operator:

Operation:

Example:

Result:

&

AND

a & b

1 if both bits are 1

|

OR

a | b

1 if either bit is 1

^

XOR

a ^ b

1 if both bits differ

~

NOT

~a

Inverts the bits

<<

Left shift

n << p

Moves n bits p left

>>

Right shift

n >> p

Moves n bits p right

For example, using the bitwise & operator in binary arithmetic:

 

53

=

00110101

&

7

=

00000111

 

5

=

00000101

image

Don’t confuse the logical AND operator && with the bitwise & operator, or the logical OR operator || with the bitwise | operator.

A common use of bitwise operators combines several values in a single variable for efficiency. For instance, a program with eight “flag” int variables, with values of 1 or 0 (representing on and off states), requires 32 bits of memory for each variable – 256 bits in total. These values only really require a single bit, however, so eight flags can be combined in a single byte variable – using one bit per flag. The status of each flag can be retrieved with bitwise operations:

imageStart a new program named “Bitwise” containing the standard main method

class Bitwise

{

public static void main( String[] args ) {       }

}

image

Bitwise.java

imageBetween the curly brackets of the main method, insert this code to declare and initialize a byte variable with a value representing the total status of up to eight flags

byte fs = 53 ; // Combined flag status of 00110101

imageAdd these lines to retrieve the status of each flag

System.out.println(“Flag 1: “+(( (fs&1)>0) ? “ON” : “off”));

System.out.println(“Flag 2: “+(( (fs&2)>0) ? “ON” : “off”));

System.out.println(“Flag 3: “+(( (fs&4)>0) ? “ON” : “off”));

System.out.println(“Flag 4: “+(( (fs&8)>0) ? “ON” : “off));

System.out.println(“Flag 5: “+(( (fs&16)>0)? “ON” : “off”));

System.out.println(“Flag 6: “+(( (fs&32)>0)? “ON” : “off”));

System.out.println(“Flag 7: “+(( (fs&64)>0)? “ON” : “off”));

System.out.println(“Flag 8: “+(( (fs&128)>0)?“ON”: “off”));

imageSave the program as Bitwise.java then compile and run the program:

image

image

How it works –The binary representation of 53 is 00110101 so the set bits are... 1 + 4 + 16 + 32 = 53

image

Here, the bitwise & operation returns one or zero to determine each flag’s status.

Summary

Arithmetical operators can form expressions with two operands for addition +, subtraction , multiplication *, division /, or modulus %.

Increment ++ and decrement -- operators modify a single operand by a value of one.

The assignment = operator can be combined with an arithmetical operator to perform an arithmetical calculation then assign its result.

Comparison operators can form expressions comparing two operands for equality ==, inequality !=, greater >, or lesser < values.

The assignment = operator can be combined with the greater than > or lesser than < operator to also return true when equal.

Logical && and || operators form expressions evaluating two operands to return a Boolean value of either true or false.

The logical ! operator returns the inverse Boolean value of a single operand.

A conditional ? : operator evaluates a given Boolean expression and returns one of two operands, depending on its result.

Expressions evaluating a Boolean expression for a true value may optionally omit == true.

It is important to explicitly set operator precedence in complex expressions by adding parentheses ( ).

The backslash escape \ operator can be used to prefix quote characters within String values to prevent syntax errors.

Escape sequences \n newline and \t tab provide simple output formatting.

Bitwise operators can be useful to perform binary arithmetic in specialized situations.