Operators in Java
after getting familar with various values and data types supported by Java, let us learn how to use them in expressions:
‘an expression is built using variables, literals or values. Operators are symbols which are used in expressions to perform
“snthmetic of logical operations. The variable or literal on which the operator is applied is known as an operand. The
‘operator needs one or more operands to perform any operation as shown in Figure 4.1.
[operand] [Operator] [[Operand)] [Operator] [ Operend ]
i ] | | |
oe il i
: Operand and Operator
Figure 4
Bll 4.1 Form of Operators
‘There are three forms of operators in Java as described in the following subsections.
4.1.1. Unary Operator
{An operator that has just one operand is known as a unary operator. Examples of unary operators are +, ~, ++ ~ |, et
4.1.2 Binary Operator
‘An operator that has two operands is known as a binary operator. Examples of binary operators are +, %, >, && etc
4.1.3 Ternary Operator
‘An operator that has three operands is known as a ternary operator. An example of ternary operator
Hl 4.2 Types of Operators
4.2.1 Arithmetic Operators
‘As in most other languages, Java allows you to form expressions using variables, constants, and the arithmetic operators:
+ (addition), ~ (subtraction), * (multiplication), / (division), and % (modulus, remainder). Table 1 lists the arithmetic
operators available in Java.
eo
eS 5
x+y
Table 1: Arithmetic Operators
Let us go through these operators in more detail.
1, Addition Operator (+)
‘The addition operator adds the two operands, thereby giving the sum of two values. For example,
25 + Tevaluates to 32
‘Computer Applications X tis | (53) i
Scanned with CamScannerz
12 evaluates to 22 (when z= 10)
(when x= 12 and y = 8)
data type (byte, short, int, Long) or the floating point data type (float, doubl;
X + y evaluates to 20
The operands may be of the integer
2. Subtraction Operator (-)
a cece subtracts the second operand from the first, thereby giving the difference between the tw:
19 - 8 evaluates to11
Z - 12 evaluates to-7 (when z= 5)
X = yevaluates to 3 (when x= 7 and y=4)
The operands may be ofthe integer datatype (byte, short, int, Long) or the Noting point datatype (Noa, do
a for the addition operator.
3. Division Operator (/)
The division operator divides the first operand by the second ‘operand, thereby giving the quotient.
If both the operands are integers then the result of the division will also be an integer, i.e., the decimal par
truncated (removed). However, when either of the operands or both are float or double, the result of the division i
number. For example,
38/5 results in 7 (integer division)
38/5.0 results in 7.6 (real division)
38.0/5 results in 7.6 (real division)
38.0/5.0 results in 7.6 (real division)
Remainder or Modulus Operator (%)
remainder 2, i.e., 20 % 3 results in 2
Similarly, x % 5 results in 3, when x = 23,
/* ArithmeticOperators.java */
public class ArithmeticOperators
public static void main(String args(])
{
int x=13, y=
system.out.print1n("xty evaluates to " + (x+y);
system.out.printIn("x-y evaluates to " + (x-y));
system. out .printIn("x*y evaluates to
System.out.println("x/y evaluates to
System.out.println("x%y evaluates to?
to the binary form, the plus and minus operators also have a unary form where they can operate on just one
as detailed below.
unary + Operator
‘The unary plus operator (+) is written before the operand. This operator results in the same value as the operand. For
‘example:
ifx = 15, then +x results in 15.
{fx = -7, then +x results in -7.
fx = @ then 4x results in 0.
Unary - Operator
The unary minus operator (-) also precedes an operand. This operator negates the value of an operand, i.e. if an operand
isa positive value, it converts the value of that operand to its negative value and vice-versa.
fx = 15,then -x results in-15.
fx = -7,then -x results in 7.
fx
String Operator (+)
‘You have already seen how the + sign can be used to concatenate’ strings. Some other examples of concatena'
@, then -x results in 0.
tion are as
follows:
"6" + "5" will result in "65"
"Room "+ "39" will result in "Room 39"
result in"15 August”
"15 "+ "August"
4.2.2 Relational Operators
Relational operators determine the relationship between the two operands by comparing them. The outcome of these
‘operations is a boolean value which is either true or False. Java provides six types of relational operators as shown in
Table 2. Relational operators are binary operators as they operate on two operands.
Table 2: Relational Operators
/* RelationalOperators.java */
blic class RelationalOperators
“public static void main(String ares{])
TConcatenation is the process of joining two strings together.
_ Operators in Java kins | (35
Scanned with CamScannerea
- +2 Saisie
OER ayia: false
+ (x= YDS
"4x ey)
4 (x te ys
int x = 23, y = 175
System.out.printin("x > y is
System.out.printin("x < y is:
System.out.printin("x == y is
System.out.printin("x >= y is:
System.out.printin("x <= y is:
System.out.printIn("x != y is:
x>=yis: true
x <= yis: false
x!=yis: tue
}
}
Note that relational operators have lower priority than the arithmetic operators
4.2.3 Logical Operators ision-making expressi
Logical operators operate only on boolean operands and are used to construct complex decision :
following table lists some of the logical operators.
Operator
Logical AND
Logical OR
Logica ior, aaa
Table 3: Logical Operators
1. Logical AND Operator (&&)
The logical AND operator (8&) is a binary operator and is used to combin
value is a boolean value. The result is true if both the values are true, an
false. Table 4 shows the Truth Table for the AND operator:
operandi && operand2
true
1e two conditions or expressions. T!
id the result is false if either of
It has the following syntax:
true
‘Table 4: AND Operator Truth Table
Let us take an example as follows:
(25 > 33) && (25 < 27)
This will evaluate as:
false && true > false
The result is false because the first expression evaluates to false.
Note that the logical AND operator has lower priority than the relational operators.
2. Logical OR Operator (||)
The logical OR operator (||) is a binary operator and is used to combine two conditions or expressions. The res:
is also a boolean value. The result is true if either of its operands is true, or if both are true. Table 5 sho.
Table for the OR operator.{thas the following syntax:
operandi || operand?
Result of
Cee
true true true
true false true
false true true
false false false
Table 5: OR Operator Truth Table
For example, consider the expression:
(38 > 33) || (33< 33)
This evaluates to:
true || false> true
‘Note that the logical OR operator has lower priority than the relational operators.
3. Logical NOT Operator (!)
‘The logical NOT operator (1) is a unary operator and is written before a single op*
the result of the expression following it, ie, if the expression returns a true value then the logical NOT operator will
return false, and vice versa. Table 6 shows the Truth Table for the NOT operator.
Result of
operand
true false
false true
yerand, The logical NOT operator negates
Ithas the following syntax:
loperand
‘Table 6: NOT Operator Truth Table
For example, consider the expression:
1(23> 43)
This evaluates to:
Halse > true
Note that the logical NOT operator has higher precedence than the relational and arithmetic operators.
Let us now learn the implementation of the logical operators with the help of the following program.
Bee)
7* Logicalperators. java */
public class Logicaloperators
{
public static void main(String args[])
{
System. out .printIn("(25 > 33) && (25 < 27) is “ + ((25 > 33) && (25 < 27)));
‘System. out .println("(38 > 33) || (33 < 33)) is ” + ((38 > 33) || (33 < 33)))5
‘Operators in Java Kivs| (57 )
Scanned with CamScannerSystem.out.printin("!(23 > 43) is ” + (1(23 > 43)))5
(25 > 33) 88 (25 < 27) is false
(28 > 33) 1 (93 <33))istue
| "23> 43) is tue
4.2.4 Assignment Operators
‘Assignment operator is used to assign the value of an expression to a variable. It has the following syntax
variable = expression;
For example, consider the following assignment:
totalMarks = 780;
The value of totalmarks after assignment will be 780. Any previous value stored in the totalMarks is destrc
replaced by the new value.
Let us see another example:
counter = counter + 1;
and adding 1 to it. Finally, it will store the answer as the new value of the counter.
The assignment operator is a binary operator.
Difference between = and
The = operator is an assignment operator. It sets a variable equal to some value, For example, age =15 sets
named age equal to 15,
The == operator is @ comparison operator. You use it to check if something equals something else. For example
age == 17 checks if the value that age holds is equal to 17.
1, Shorthand Assignment Operators
Java offers several variations of the assignment operator that are referred to as shorthand assignment oper
example, consider the following statement: ope
x= x +25
You can rewrite the above assignment statement as:
x
2;
This version of the statement uses 4= shorthand assignment operator. Both
value of variable x by 2. Assuming that the initial value of x was 7, the new
of the above statement.
Perform the same action, ie., incren
value of x will be 9 (742) after the ex
Java offers shorthand assignment operators for all the arithmetic bi
ina
includes the following syntax: iY operators. Therefore, any stateme
th CamScannervariable = variable operation expression;
can be rewritten, using the shorthand operator, as:
variable operation= expression;
For example, x = x + 3; canberewritten as, x += 3;
‘There are two advantages of using shorthand assignment operators as given below:
i. They save a little bit of typing time.
jj, The use of shorthand operators results in an efficient code as they are implemented most efficiently by the Java
run-time environment as compared to their long forms.
‘The following table shows the main shorthand operators.
Cod
Been)
/* ShorthandOperators.java */
{
{
int x, y3
x= 10; y= 33
System. out. print1n("x
x = 10; y = 35
system.out.print1n("x
x = 10; y = 3;
system. out .print1n("x
x = 10; y = 33
System. out.print1n("x
x= 10; y= 35
system. out .print1n(”x
Java
public static void main(string
public class Shorthandoperators
42 1is
-= Lis
wey is
zy is
we y is
ares[])
+x
+ (x
+
+ (x
1))5
1))5
= y))3
y))5
yy)
Pee per ee)
ere erated
a
Scanned with CamScannervalue of x. The
+ are the sami
J as expressions
‘Scanned with CamScannertnt yt oty = 15,
rat se (y1) thon creme
++ Final value of z= 15, y= 16 a gees
Figure 4.2: Postfix Expression Evaluation
= in the Postfix increment; first use, then increment.
Figure 4.3 shows the memory status during the evaluation process.
a -
b. ae 15 ——+ First use y }
Figure 4.3: Postfix Increment
Let us understand this process step by step.
‘a. Initially, the value of variable y is 15, and the value of variable z is not defined.
'b. Asitis a Postfix operation, you first use y, which is 15, hence zis assigned the value 15.
¢. Now, you increment the value of y by 1. Thus, the final value of y = 16.
‘The following program isthe implementation of Figure 4.3.
public class Postfixincrement
{
public static void main(string args(])
{
int y = 15;
int z = y+; y: 16
system.out.printin("y: "+ ys ee
system.out.println("z: "+ 2)5
t
p)
Now, consider the following statement
z= Hy;
Here, ++y is defined to be the new valu
ice, it first increments the value of y and then uses its value as sh
Je of y after 1 has been added. So ify is 15 then both y and z wllhave the value 16,
yown in Figure 4.4.
sina value of y= 15
naval ott cay trt increment (y=¥6) then use
‘Final value of z= 16, y= 16
Figure 4.4: Profix Expression Evaluation
‘Kips | 61)
Scanned with CamScannereset {Remember the rule in the Prefix increment: first increment, then Use.
Figure 4.5 shows the memory status during the evaluation process
2 y c
fay = 15:
; is ss :
: A ristincrement Y } ae |
16 » Then use
Figure 4.5: : Prefix nerement
Here is the stepwise explanation of what happens:
ithas not been declared
a Initial, the value of variable ys 15, and the vlue of variable zs undefined #518 P3526 E
rat incremented, thus the valueofy becomes 26: The
b, When you use the prefix operation, the value i fi
remains undefined since the value of y has not been used yet.
5 16
c. After incrementing, the value of y is used, ie, assigned to, Thus, z become:
The following program is the implementation of Figure 4.5:
public class Prefixincrenent
{
public static void main(String args[])
{
int z = +5
system. out .printin("y
1
2
3
4
5 int y = 15;
6
7
8 system, out .printin("2:
98
10 }
In short, we can say:
+ The postfix operator first assigns the value to the variable on the left and then increments the value of t!
+ The prefix operator fist increments the value of the operand and then assigns it to the variable on the
4.2.6 Conditional Operator (?:)
The conditional operator is also called a ternary operator because it has three operands. Its syntax is:
boolean-expression ? expressiont : expression?
The operator works as follows: the boolean- expression is evaluated firs. Ifit evaluates to true, then the
entire expression is expressiont; otherwise, the value ofthe entire expression is expression2, Note that or
the expressions (either expressiond or oe is evaluated,
program.
62 } | Kies
th CamScanner/* FindMin.java */
public class FindMin
.
public static void main(String args{])
{ Minimum number is: 113
int a = 127, b = 113;
System.out.printIn("Ninimum number is: " + ((a 25000 || salary <= seeee
+ option == ‘A’ || option == 'B'
ta b && a f=
a