Date post: | 22-May-2015 |
Category: |
Documents |
Upload: | dhrubo-kayal |
View: | 452 times |
Download: | 1 times |
OperatorsDhrubojyoti Kayal
What is an operator? Precedence Assignment operator Mathematical operators Increment & Decrement operator Relational operators Logical operator Ternary operator String operator Casting operator
Agenda
Symbol representing an operation – mathematical, character etc
Needs one or more operands to produce result A + B 10 + 20 Operator can produce result Operator can change the value of the operand
(side effect) Operators, operands and parenthesis combine
to form expressions
What is an operator?
Mostly mathematical Binary – takes two arguments: +,-,*,/ Unary – takes one argument: -,! Boolean operators: ! String: + Bitwise & Shift: Left outs Work mostly with primitives Some operators work with objects too =,==
Java operators
Defines how an expression evaluates when several operators are present
Java has specific rules that determine the order of evaluation
multiplication and division happen before addition and subtraction
Use parentheses to make the order of evaluation explicit
Precedence
public class Precedence { public static void main(String[] args) { int x = 1, y = 2, z = 3; int a = x + y - 2/2 + z; // (1) int b = x + (y - 2)/(2 + z); // (2) System.out.println("a = " + a + " b = " + b); }
} /* Output: a = 5 b = 1
Precedence Test
= int a = 4; Take the value of the right-hand side (often
called the rvalue) and copy it into the left-hand side (often called the lvalue)
An rvalue is any constant, variable, or expression that produces a value.
An lvalue must be a distinct, named variable.
Rectangle rectangle = new Rectangle();
Assignment Operator
+ , - , * , / , % Operate and assign
◦ += ,-=,*=,/=,% Unary operators
◦ - (inverts the sign on the operand),+ (useless)◦ x = -a; ◦ x = a * (-b);
Mathematical Operators
Exercise
Write a Java program to declare to int variables and assign them literal values
Perform different mathematical operations and assign the values to result variables
Print the operands and results Print : System.out.println(5/2) Integer division special feature
++ : increase by one unit -- : decrease by one unit a = 5; b = a++; //post-increment : assign
increase b = a--; //pre-increment : assign decrease b = ++a; b = --a;
Increment Decrement Operator
Exercise
Generate a boolean result They evaluate the relationship between the
values of the operands A relational expression produces true if the
relationship is true, and false if the relationship is untrue
less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equivalent (==) and not equivalent (!=)
Relational Operators
Exercise
Write a simple Java program and declare two int variables.
Assign them values Try out the relational operators one by one
◦ System.out.println(a>b); Check out equivalence with Objects
Integer n1 = new Integer(47);
Integer n2 = new Integer(47); System.out.println(n1 == n2); System.out.println(n1 != n2);
Equivalence ◦ Compare object references not values◦ Override equals method that exist with all objects
Works on boolean operands Logical operators AND (&&), OR (||) and NOT
(!) produces a boolean value of true or false based on the logical relationship of its arguments
(A > B) && (C > D) (A > B) || (C > D) !A
Logical Operators
Continue from relational operator exercise and declare two more int variables
Now try &&, || and !
Exercise
Expression will be evaluated only until the truth or falsehood of the entire expression can be unambiguously determined
The latter parts of a logical expression might not be evaluated
Short circuit
public class ShortCircuit { static boolean test1(int val) { s.o.p("result: " + (val < 1)); return val < 1; } static boolean test2(int val) { s.o.p("result: " + (val < 2)); return val < 2; } static boolean test3(int val) { s.o.p("result: " + (val < 3)); return val < 3; } public static void main(String[] args) { boolean b = test1(0) && test2(2) && test3(2);
s.o.p("expression is " + b);
} }
Short circuit blow-up
One special usage of an operator in Java The + and += operators can be used to
concatenate strings Operator overloading String a = “AIR”; String b = “INDIA” System.out.println(a + b); int c = 747 System.out.println(a + b + c);
String Operators
Conditional operator, is unusual because it has three operands.
It is truly an operator because it produces a value, unlike the ordinary if-else
boolean-exp ? value0 : value1 If boolean-exp evaluates to true, value0 is
evaluated, and its result becomes the value produced by the operator.
If boolean-exp is false, value1 is evaluated and its result becomes the value produced by the operator.
Ternary Operator
int a = 5;int b = 6;int c = (a > b) ? a : b ;
Try out ternary operator
Casting into a mold Automatically change one type of data into
another when appropriate◦ if you assign an integral value to a floating point
variable, the compiler will automatically convert the int to a float
Casting allows you to make this type conversion explicit, or to force it when it wouldn’t normally happen.
To perform a cast, put the desired data type inside parentheses to the left of any value.
Casting Operators
int i = 200; long lng = (long)i; lng = i; // "Widening," so cast not really
required long lng2 = (long)200; lng2 = 200; // A "narrowing conversion": i = (int)lng2; // Cast required
Casting Operators
It’s possible to perform a cast on a numeric value as well as on a variable
You can introduce superfluous casts; for example, the compiler will automatically promote an int value to a long when necessary. However, you are allowed to use superfluous casts to make a point or to clarify your code
In other situations, a cast may be essential just to get the code to compile.
Java allows you to cast any primitive type to any other primitive type, except for boolean, which doesn’t allow any casting at all.
Cast works with Objects too.◦ Circle circle = (Circle) shape;
Casting Operators
If you cast from a floating point value to an integral value, what does Java do? double above = 0.7, below = 0.4;
float fabove = 0.7f, fbelow = 0.4f;
print("(int)above: " + (int)above);
print("(int)below: " + (int)below);
print("(int)fabove: " + (int)fabove);
Casting from a float or double to an integral value always truncates the number.
If instead you want the result to be rounded, use the round( ) methods in java.lang.Math print("Math.round(above): " + Math.round(above)); print("Math.round(below): " + Math.round(below)); print("Math.round(fabove): " + Math.round(fabove));
Truncation & Rounding
If you perform any mathematical or bitwise operations on primitive data types that are smaller than an int (that is, char, byte, or short), those values will be promoted to int before performing the operations, and the resulting value will be of type int.
You want to assign back into the smaller type, you must use a cast and take care of data loss
In general, the largest data type in an expression is the one that determines the size of the result of that expression; ◦ if you multiply a float and a double, the result will be
double; if you add an int and a long, the result will be long.
Promotion
Q&A