# OpenStax-CNX

You are here: Home » Content » Jb0210: Java OOP: Operators

### Recently Viewed

This feature requires Javascript to be enabled.

# Jb0210: Java OOP: Operators

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: Earlier modules have touched briefly on the topic of operators. This module discusses Java operators in depth.

## Preface

Earlier modules have touched briefly on the topic of operators . This module discusses Java operators in depth.

### Viewing tip

I recommend that you open another copy of this module in a separate browser window and use the following links to easily find and view the listings while you are reading about them.

## Introduction

The first step in learning to use a new programming language is usually to learn the foundation concepts such as

• variables,
• operators,
• types,
• expressions,
• flow-of-control, etc.

This module concentrates on the operators used in Java.

## Operators

Unary and binary operators

Java provides a set of operators that can be used to perform an action on one, two, or three operands. An operator that operates on one operand is called a unary operator. An operator that operates on two operands is called a binary operator. An operator that operates on three operands is called a ternary operator.

Some operators can behave either as a unary or as a binary operator. The best known such operator s probably the minus sign (-) . As a binary operator, the minus sign causes its right operand to be subtracted from its left operand. As a unary operator, the minus sign causes the algebraic sign of the right operand to be changed.

A ternary operator

Java has only one operator that takes three operands. It is a conditional operator, which I sometimes refer to as a cheap if statement.

The first operand is a boolean expression, which is followed by a question mark character (?) . The question mark is followed by a second operand, which is followed by a colon character (:) . The colon character is followed by the third operand.

If the boolean expression evaluates to true, the value of the operand following the ? is returned. Otherwise, the value of the operand following the : is returned.

An example of the syntax follows:

### Note:

Ternary operator syntax

boolean expression ? value1 : value2

Unlike C++, Java does not support the creation of overloaded operators in program code. (If you don't know what this means, don't worry about it.)

Operators from previous programs

The statements in the following note box illustrate the use of the following operators from Java programs in earlier modules :

• =
• !=
• +
• (char)

### Note:

Operators from previous programs

int ch1, ch2 = '0';
while( (ch1 = System.in.read() ) != '#') ch2 = ch1;
System.out.println("The char before the # was "
+ (char)ch2);

The plus and cast operators

Of particular interest in this list is the plus sign (+) and the cast operator (char) .

In Java, the plus sign can be used to perform arithmetic addition. It can also be used to concatenate strings. When the plus sign is used in the manner shown above , the operand on the right is automatically converted to a character string before being concatenated with the operand on the left.

The cast operator is used in this case to purposely convert the integer value contained in the int variable ch2 to a character type suitable for concatenating with the string on the left of the plus sign. Otherwise, Java would attempt to convert and display the value of the int variable as a series of digits representing the numeric value of the character because the character is stored in a variable of type int .

The increment operator

An extremely important unary operator is the increment operator identified by two plus characters with no space between them (++) .

The increment operator causes the value of its operand to be increased by one.

### Note:

The decrement operator

There is also a decrement operator (--) that causes the value of its operand to be decreased by one.

The increment and decrement operators are used in both prefix and postfix notation.

Prefix and postfix increment and decrement operators

With the prefix version, the operand appears to the right of the operator ( ++X) , while with the postfix version, the operand appears to the left of the operator (X++) .

What's the difference in prefix and postfix?

The difference in prefix and postfix has to do with the point in the sequence of operations that the increment (or decrement) actually occurs if the operator and its operand appear as part of a larger overall expression.

(There is effectively no difference if the operator and its operand do not appear as part of a larger overall expression.)

Prefix behavior

With the prefix version, the variable is incremented (or decremented) before it is used to evaluate the larger overall expression.

Postfix behavior

With the postfix version, the variable is used to evaluate the larger overall expression before it is incremented (or decremented) .

Illustration of prefix and postfix behavior

The use of both the prefix and postfix versions of the increment operator is illustrated in the Java program shown in Listing 1 . The output produced by the program is show in the comments at the beginning of the program.

1
Listing 1: Illustration of prefix and postfix notation.

Illustrates the use of the prefix and the postfix increment
operator.

The output from the program follows:

a = 5
b = 5
a + b++ = 10
b = 6

c = 5
d = 5
c + ++d = 11
d = 6

*********************************************************/
class incr01 { //define the controlling class
public static void main(String[] args){ //main method
int a = 5, b = 5, c = 5, d = 5;
System.out.println("a = " + a );
System.out.println("b = " + b );
System.out.println("a + b++ = " + (a + b++) );
System.out.println("b = " + b );
System.out.println();

System.out.println("c = " + c );
System.out.println("d = " + d );
System.out.println("c + ++d = " + (c + ++d) );
System.out.println("d = " + d );
}//end main
}//End incr01 class.


Binary operators and infix notation

Binary operators use infix notation, which means that the operator appears between its operands.

General behavior of an operator

As a result of performing the specified action, an operator can be said to return a value (or evaluate to a value) of a given type. The type of value returned depends on the operator and the type of the operands.

### Note:

Evaluating to a value

To evaluate to a value means that after the action is performed, the operator and its operands are effectively replaced in the expression by the value that is returned.

Operator categories

I will divide Java's operators into the following categories for further discussion:

• arithmetic operators
• relational and conditional (logical) operators
• bitwise operators
• assignment operators

### Arithmetic operators

Java supports various arithmetic operators on all floating point and integer numbers.

The binary arithmetic operators

The following table lists the binary arithmetic operators supported by Java.

#### Note:

The binary arithmetic operators

Operator    Description

-        Subtracts the right operand from the left
operand
*        Multiplies the operands
/        Divides the left operand by the right operand
%        Remainder of dividing the left operand by
the right operand

String concatenation

As mentioned earlier, the plus operator (+) is also used to concatenate strings as in the following code fragment:

#### Note:

String concatenation

"MyVariable has a value of  "
+ MyVariable + " in this program."

Coercion

Note that this operation also coerces the value of MyVariable to a string representation for use in the expression only. However, the value stored in the variable is not modified in any lasting way.

Unary arithmetic operators

Java supports the following unary arithmetic operators.

#### Note:

Unary arithmetic operators


Operator    Description

+        Indicates a positive value
-        Negates, or changes algebraic sign
++       Adds one to the operand,
both prefix and postfix
--       Subtracts one from operand,
both prefix and postfix

The result of the increment and decrement operators being either prefix or postfix was discussed earlier .

### Relational and conditional (logical) operators

Binary Relational operators

Java supports the set of binary relational operators shown in the following table. Relational operators in Java return either true or false as a boolean type.

#### Note:

Binary Relational operators

Operator    Returns true if
>        Left operand is greater than right operand
>=       Left operand is greater than or equal to
right operand
<        Left operand is less than right operand
<=       Left operand is less than or equal to
right operand
==       Left operand is equal to right operand
!=       Left operand is not equal to right operand

Conditional expressions

Relational operators are frequently used in the conditional expressions of control statement such as the one in the code fragment shown below.

#### Note:

Conditional expressions

if(LeftVariable <= RightVariable). . .

Illustration of relational operators

The program shown in Listing 2 illustrates the result of applying relational operators in Java. The output is shown in the comments at the beginning of the program. Note that the program automatically displays true and false as a result of applying the relational operators.

2
Listing 2: Illustration of relational operators.

Illustrates relational operators.

Output is

The relational 6<5 is false
The relational 6>5 is true

*********************************************************/
class relat01 { //define the controlling class
public static void main(String[] args){ //main method
System.out.println("The relational 6<5 is "
+(6<5));
System.out.println("The relational 6>5 is "
+(6>5));
}//end main
}//End relat01 class.


Conditional operators

The relational operators are often combined with another set of operators (referred to as conditional or logical operators) to construct more complex expressions.

Java supports three such operators as shown in the following table.

#### Note:

Conditional or logical operators

Operator  Typical Use            Returns true if
&&     Left && Right     Left and Right are both true
||     Left || Right     Either Left or Right is true
!      ! Right           Right is false

The operands shown in the table must be boolean types, or must have been created by the evaluation of an expression that returns a boolean type.

Left to right evaluation

An important characteristic of the behavior of the logical and and the logical or operators is that the expressions are evaluated from left to right, and the evaluation of the expression is terminated as soon as the result of evaluating the expression can be determined.

For example, in the following expression, if the variable a is less than the variable b , there is no need to evaluate the right operand of the || to determine that the result of evaluating the entire expression would be true . Therefore, evaluation will terminate as soon as the answer can be determined.

#### Note:

Left to right evaluation

(a < b) || (c < d)

Don't confuse bitwise and with logical and

As discussed in the next section, symbols shown below are the bitwise and and the bitwise or .

#### Note:

Bitwise and and bitwise or

& bitwise and
| bitwise or

One author states that in Java, the bitwise and operator can be used as a synonym for the logical and and the bitwise or can be used as a synonym for the logical inclusive or if both of the operands are boolean . (I recommend that you don't do that because it could cause confusion for someone reading your code.)

Note however that according to a different author, in this case, the evaluation of the expression is not terminated until all operands have been evaluated, thus eliminating the possible advantage of the left-to-right evaluation.

### Bitwise operators

Java provides a set of operators that perform actions on their operands one bit at a time as shown in the following table.

#### Note:

Bitwise operators

Operator   Typical Use         Operation

>>     OpLeft >> Dist      Shift bits of OpLeft right
by Dist bits (signed)
<<     OpLeft << Dist      Shift bits of OpLeft left
by Dist bits
>>>    OpLeft >>> Dist     Shift bits of OpLeft right
by Dist bits (unsigned)
&      OpLeft & OpRight    Bitwise and of the
two operands
|      OpLeft | OpRight    Bitwise 

Populating vacated bits for shift operations

The signed right shift operation populates the vacated bits with the sign bit, while the left shift and the unsigned right shift populate the vacated bits with zeros.

In all cases, bits shifted off the end are lost.

The rule for bitwise and

The bitwise and operation operates according to the rule that the bitwise and of two 1 bits is a 1 bit.

Any other combination results in a 0 bit.

Bitwise inclusive or

For the inclusive or , if either bit is a 1, the result is a 1.

Otherwise, the result is a 0.

Bitwise exclusive or

For the exclusive or , if either but not both bits is a 1, the result is a 1.

Otherwise, the result is a 0.

Another way to state this is if the bits are different, the result is a 1. If the two bits are the same, the result is a 0.

The complement operator

Finally, the complement operator changes each 1 to a 0 and changes each 0 to a 1.

### Assignment operators

Simple assignment operator

The (=) is a value assigning binary operator in Java. The value stored in memory and represented by the right operand is copied into the memory represented by the left operand.

Using the assignment operator with reference variables

You need to be careful and think about what you are doing when you use the assignment operator with reference variables in Java. If you assign one reference variable to another, you simply end up with two reference variables that refer to the same object. You do not end up with two different objects.

(If what you need is another copy of the object, you may be able to use the clone method to accomplish that.)

Shortcut assignment operators

Java supports the following list of shortcut assignment operators. These operators allow you to perform an assignment and another operation with a single operator.

#### Note:

Shortcut assignment operators

+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=
>>>=


For example, the two statements that follow perform the same operation.

#### Note:

Illustration of shortcut assignment operation

x += y;
x = x + y;

## Miscellaneous

This section contains a variety of miscellaneous information.

### Note:

Housekeeping material
• Module name: Jb0210: Java OOP: Operators
• File: Jb0210
• Originally published: 1997
• Published at cnx.org: 11/23/12
• Revised: 01/02/13

### Note:

Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

-end-

## Content actions

### Give feedback:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

#### Definition of a lens

##### Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

##### What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

##### Who can create a lens?

Any individual member, a community, or a respected organization.

##### What are tags?

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks