Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
LECTURE 3
Java Operators
What are Operators?
• Operators are special symbols used for
– mathematical functions
– assignment statements
– logical comparisons
• Examples:
3 + 5
14 + 5 – 4 * (5 – 3)
// uses + operator
// uses +, -, * operators
• Expressions can be combinations of variables,
primitives and operators that result in a value
The Operator Groups
There are 5 different groups of operators:
Arithmetic operators
Assignment operator
Increment/Decrement operators
Relational operators
Conditional operators
Arithmetic Operators
Java has 5 basic arithmetic operators
+
addition
*
/
subtraction
multiplication
division
%
modulos (remainder)
Precedence and Associativity of Operators
Operators
Associativity
Type
*
/
Left to right
Multiplicative
+
-
Left to right
Additive
<
<=
Left to right
Relational
== !=
Left to right
Equality
=
Right to left
Assignment
%
>
>=
Unary and Binary Operators
The plus (+) and minus (–) operators can be both
unary and binary
A unary operator has only one operand
A binary operator has two operands
For example, the – operator in -7 can be considered a
unary operator to negate the number 7
The – operator in 3 – 7 is a binary operator for
subtracting 7 from 3
Order of Operations
Example: 10 + 15 / 5;
The result is different depending on whether the
addition or division is performed first
(10 + 15) / 5 = 5
10 + (15 / 5) = 13
Without parentheses, Java will choose the second
case
Note: You should be explicit and use parentheses
to avoid confusion
Integer Division and Modulus
The result of an integer division is an integer
The fractional part is truncated
In the previous example, we learned that (10 +
15) / 5 gives an exact integer answer (5).
But what if we divide 63 by 35?
Depending on the data types of the variables that
store the numbers, we will produce different results.
Integer Division Example
int i = 63;
int j = 35;
System.out.println(i / j);
Output: 1
double x = 63;
double y = 35;
System.out.println(x / y);
Output: 1.8
The result of an integer division is just the integer
part of the quotient!
The Modulus Operator
When an integer is divided by another integer the
result is another integer
26 / 5 produces an integer value 5
To obtain the remainder, the modulus is used
An example is 26 % 5 and the result is 1
The modulus operator produces the remainder after
an integer division
Finding the modulus can be very useful
The modulus operator can be used in loops to track
certain pattern of code execution
What’s wrong?
When I divide 5/3, I get 1. What’s wrong?
The integer divisions always result in integer values
In order to obtain a fractional return value please
use a float or a double.
An example is 5.0 / 3.0 produces approx 1.6666667
Integer division in java is different from everyday
integer division in algebra
The Assignment Operator
The basic assignment operator (=) assigns the
value of expression to variable
variable = expression ;
Java allows you to combine arithmetic and
assignment operators into a single operator.
Examples:
x = x + 5; is equivalent to
y = y * 7; is equivalent to
x += 5;
y *= 7;
Shortcut operators
Operator
Name
Example
Equivalent
+=
Addition assignment
i += 5;
i = i + 5;
-=
Subtraction assignment
i -= 5;
i = i -5;
*=
Multiplication assignment
i *= 5;
i = i * 5;
/=
Division assignment
i /= 5;
i = i / 5;
%=
Remainder assignment
i %= 5;
i = i % 5;
Increment/Decrement Operators
count = count + 1; is equivalent to
and can be written as:
++count; or count++;
count += 1;
++ is called the increment operator.
count = count - 1; is equivalent to
and can be written as:
--count; or count--;
-- is called the decrement operator.
count -= 1;
Operator precedence
Highest order
Lowest order
var++ and var-- (postincrement and postdecrement)
+, - (Unary plus and minus), ++var and –var (prefix)
(type) (Casting)
! (Not)
*, /, % (Multiplication, Division, Remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, != (Equality)
& (Unconditional AND)
^ (Exclusive OR)
| (Unconditional OR)
&& (Conditional AND)
|| (Conditional OR)
=, +=, -=, *=, /=, %= (Assignment operator)
The increment/decrement operator has two forms:
The prefix form ++count, --count
first adds 1 to the variable and then continues to any other operator in the
expression
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = ++numOranges + numApples;
numFruit has value 16
numOranges has value 6
The postfix form count++, count--
first evaluates the expression and then adds 1 to the variable
int numOranges = 5;
int numApples = 10;
int numFruit;
numFruit = numOranges++ + numApples;
numFruit has value 15
numOranges has value 6
Numeric Type Conversion
Arithmetic operations that involve data of the same
type produce results of same type
An int divided by another int results in an int
Certain computation involves numeric data of unlike
types (say a double added to an int)
When an operation involves operands of unlike types,
Java chooses a unifying type for the result
The conversion to the unifying type occurs before the
operation takes place to produce the result
Java has the ability to automatically convert unlike
operands to a unifying type
Type Conversion contd
Numeric conversion of two operands of different
types occur such that
When two unlike types are used in an expression, the
unifying type is the operand with the larger range of values
Java converts the numeric data that has the lower range of
values to the data type that has the larger range of values
For example, an int, variable firstVar and a double
variable secondVar can be multiplied as follows
int firstVar = 15; double secondVar = 11.5;
double varProduct = firstVar * secondVar;
The result varProduct is a double because the int
variable firstVar was promoted to a unifying type of
higher range type double
Sample Type Unifying
class UnifyingTypes
{
public static void main( String[ ] args )
{
int varInt = 5, resultInt, resultFl;
float varFloat = 7.5f, resultFloat, resultFloatDbl;
double varDouble = 2.55, resultDoubleFl, resultDoubleDbl;
resultInt = varInt + varFloat;
// possible loss of precision
resultFl = varInt + varFloat;
// possible loss of precision
resultFloat = varInt + varFloat;
// possible loss of precision
resultFloatDbl = varFloat + varDouble; // possible loss of precision
resultDoubleFl = varInt + varFloat;
resultDoubleDbl = varFloat + varDouble;
Unifying Type Sample
System.out.println( "resultInt = " + resultInt );
System.out.println( "resultFloat = " + resultFloat );
System.out.println( "resultDoubleFl = " + resultDoubleFl );
System.out.println( "resultDoubleDbl = " + resultDoubleDbl );
}
}
The Cast Operation (Type Casting)
The unifying type process can be explicitly
overidden by type casting
Casting is an operation that converts a
value of one data type into a value of
another data type
Type casting forces a value of one data type
to be used as a value of another type
Type casting is performed by placing the
desired data type in parenthesis followed by
the variable or the constant to be casted
Type Casting Samples
Consider the following conversion
double initialValue = 246.72;
float finalValue = (float) initialValue / 3;
In the above casting, the double value initialValue / 3
is converted to a float before it is stored in the float
variable finalValue
Without the casting, the statement that assigns the
result to finalValue would not compile
Consider another example
float someMoney = 35.55f;
int anotherMoney = ( int ) someMoney;
Type Casting contd
In the previous example the float value someMoney is
converted an int value before it is stored in the integer
variable anotherMoney
When the float is converted to an int, the decimal
place values are lost
There is no need to cast a value if it is to be assigned
to a value of higher type
Consider the statement double myNumber = 10;
In the above statement, Java automatically promotes
the integer constant 10 to a double 10.0
For clarity it is desirable to write
double myNumber = 10.0;
Sample Type Casting
public class TypeCastDemo
{
public static void main( String[ ] arg )
{
// declare a float to be divided by an int value
float totalExamScore = 788.9f;
// declare an int to divide a float value
int numberOfStudents = 11;
// averageScore declared as int instead of float or double can lead to possible loss of precision
// casting totalExamScore to an int to allow division take place though precision can be lost
int averageScore = ( int )totalExamScore / numberOfStudents;
System.out.println("Averagae score is " + averageScore);
}
}
Sample Casting (with error)
public class TypeCastDemoErr
{
public static void main( String[ ] arg )
{
// declare a double to be casted to an int value
double totalExamScore = 788.9;
// declare a double to divide an int value
double numberOfStudents = 11;
// averageScore declared as int instead of a double, possible loss of precision
// assigning an int to a double result in a division will lead to an error
int averageScore = ( int )totalExamScore / numberOfStudents;
System.out.println("Averagae score is " + averageScore);
}
}
Type Casting and References
Type casting only works with primitive data
types (double, float, int, char)
Type casting does not work with class objects
such as String
String objects can be converted to numeric
types by using methods from the built-in Java
classes Integer and Double
Each primitive type in Java has a corresponding
class contained in the java.lang package
These classes are called type-wrapper classes
Using type-wrapper classes
Type-wrapper classes contain methods for
processing primitive type values
Numeric String data can be converted to integer
values by using the Intger.parseInt() method
Numeric String data can be converted to double
data by the Double.parseDouble() method
As an example a variable that contains a person’s
age in a String variable ageString can be
converted as follows:
int age = Integer.parseInt( ageString );
double weight = Double.parseDouble( weightString );
Relational (Comparison) Operators
• Relational operators compare two values
• Produces a boolean value (true or false)
depending on the relationship
operation
is true when . . .
a > b
a >= b
a == b
a != b
a <= b
a < b
a is greater than b
a is greater than or equal to b
a is equal to b
a is not equal to b
a is less than or equal to b
a is less than b
Note:
==
sign!
Examples of Relational Operations
int x = 3;
int y = 5;
boolean result;
1) result = (x > y);
now result is assigned the value false because
3 is not greater than 5
2) result = (15 == x*y);
now result is assigned the value true because the product of
3 and 5 equals 15
3) result = (x != x*y);
now result is assigned the value true because the product of
x and y (15) is not equal to x (3)
Conditional Operators
Symbol
Name
&&
AND
||
OR
!
NOT
Conditional operators can be referred to as boolean
operators, because they are only used to combine expressions
that have a value of true or false.
Truth Table for Conditional Operators
x
y
x && y
x || y
!x
True
True
True
True
False
True
False
False
True
False
False
True
False
True
True
False
False
False
False
True
Examples of Conditional Operators
boolean x = true;
boolean y = false;
boolean result;
1. Let result = (x && y);
now result is assigned the value false
(see truth table!)
2. Let result = ((x || y) && x);
(x || y)
(true && x)
evaluates to true
evaluates to true
now result is assigned the value true
Using && and ||
Examples:
(a && (b++ > 3))
(x || y)
Java will evaluate these expressions from left to
right and so will evaluate
a before (b++ > 3)
x before y
Java performs short-circuit evaluation:
it evaluates && and || expressions from left to
right and once it finds the result, it stops.
Short-Circuit Evaluations
(a && (b++ > 3))
What happens if a is false?
Java will not evaluate the right-hand expression (b++ >
3) if the left-hand operator a is false, since the result is
already determined in this case to be false. This means b
will not be incremented!
(x || y)
What happens if x is true?
Similarly, Java will not evaluate the right-hand operator y if
the left-hand operator x is true, since the result is already
determined in this case to be true.
Class Exercise
1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3;
2) What is the value of result?
int x = 8;
int y = 2;
boolean result = (15 == x * y);
3) What is the value of result?
boolean x = 7;
boolean result = (x < 8) && (x > 4);
4) What
int
int
int
is the value of numCars?
numBlueCars = 5;
numGreenCars = 10;
numCars = numGreenCars++ + numBlueCars + ++numGreeenCars;
Class Exercise
1) What is the value of number?
int number = 5 * 3 – 3 / 6 – 9 * 3;
2) What is the value of result?
int x = 8;
int y = 2;
boolean result = (15 == x * y);
-12
false
3) What is the value of result?
boolean x = 7;
boolean result = (x < 8) && (x > 4);
true
4) What
int
int
int
is the value of numCars?
numBlueCars = 5;
numGreenCars = 10;
numCars = numGreenCars++ + numBlueCars
27 + ++numGreeenCars;
References
Summary of Java operators
Order of Operations (BODMAS)
1. Brackets (Parentheses)
2. Multiplication and Division from left to right
3. Addition and Subtraction from left to right