Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 3 Java Operators.

Similar presentations


Presentation on theme: "Lecture 3 Java Operators."— Presentation transcript:

1 Lecture 3 Java Operators

2 What are Operators? Operators are special symbols used for
mathematical functions assignment statements logical comparisons Examples: // uses + operator – 4 * (5 – 3) // uses +, -, * operators Expressions can be combinations of variables, primitives and operators that result in a value

3 The Operator Groups There are 5 different groups of operators:
Arithmetic operators Assignment operator Increment/Decrement operators Relational operators Conditional operators

4 Arithmetic Operators Java has 5 basic arithmetic operators + addition
- subtraction * multiplication / division % modulos (remainder)

5 Precedence and Associativity of Operators
Type * / % Left to right Multiplicative Additive < <= > >= Relational == != Equality = Right to left Assignment

6 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

7 Order of Operations Example: 10 + 15 / 5;
The result is different depending on whether the addition or division is performed first ( ) / 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 Should give more examples during lecture. Be dynamic teachers. Eg celcius =(5/9)(fahrenheit – 32), 5/9 yields 0 in java, better 5.0/9

8 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 ( ) / 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.

9 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!

10 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

11 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 Integer division in java is different from everyday integer division in algebra

12 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 x += 5; y = y * 7; is equivalent to y *= 7;

13 Shortcut operators Operator Name Example Equivalent
+= Addition assignment -= Subtraction assignment *= Multiplication assignment /= Division assignment %= Remainder assignment i += 5; i = i + 5; i -= 5; i = i -5; i *= 5; i = i * 5; i /= 5; i = i / 5; i %= 5; i = i % 5;

14 Increment/Decrement Operators
count = count + 1; is equivalent to count += 1; and can be written as: ++count; or count++; ++ is called the increment operator. count = count - 1; is equivalent to count -= 1; and can be written as: --count; or count--; -- is called the decrement operator.

15 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)

16 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

17 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

18 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

19 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;

20 Unifying Type Sample System.out.println( "resultInt = " + resultInt ); System.out.println( "resultFloat = " + resultFloat ); System.out.println( "resultDoubleFl = " + resultDoubleFl ); System.out.println( "resultDoubleDbl = " + resultDoubleDbl ); }

21 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

22 Type Casting Samples Consider the following conversion
double initialValue = ; 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;

23 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;

24 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); }

25 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); }

26 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

27 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 );

28 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 is greater than b a >= b a is greater than or equal to b a == b a is equal to b a != b a is not equal to b a <= b a is less than or equal to b a < b a is less than b Note: == sign!

29 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); x and y (15) is not equal to x (3)

30 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.

31 Truth Table for Conditional Operators
x y x && y x || y !x True False

32 Examples of Conditional Operators
boolean x = true; boolean y = false; boolean result; Let result = (x && y); now result is assigned the value false (see truth table!) Let result = ((x || y) && x); (x || y) evaluates to true (true && x) evaluates to true now result is assigned the value true

33 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.

34 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.

35 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 is the value of numCars? int numBlueCars = 5; int numGreenCars = 10; int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars;

36 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 is the value of numCars? int numBlueCars = 5; int numGreenCars = 10; int numCars = numGreenCars++ + numBlueCars + ++numGreeenCars; -12 false true 27

37 References Summary of Java operators Order of Operations (BODMAS)
Brackets (Parentheses) Multiplication and Division from left to right Addition and Subtraction from left to right


Download ppt "Lecture 3 Java Operators."

Similar presentations


Ads by Google