OperatorsDhrubojyotiKayal
What is an operator?PrecedenceAssignment operatorMathematical operatorsIncrement & Decrement operatorRelational operatorsLogical operatorTernary operatorString operatorCasting operatorAgenda
Symbol representing an operation – mathematical, character etcNeeds one or more operands to produce resultA + B 10 + 20 Operator can produce resultOperator can change the value of the operand (side effect)Operators, operands and parenthesis combine to form expressionsWhat is an operator?
Mostly mathematicalBinary – takes two arguments: +,-,*,/Unary – takes one argument: -,!Boolean operators: !String: +Bitwise & Shift: Left outsWork mostly with primitivesSome operators work with objects too =,==Java operators
Defines how an expression evaluates when several operators are presentJava 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) { intx = 1, y = 2, z = 3; inta = 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 valuesPerform different mathematical operations and assign the values to result variablesPrint the operands and resultsPrint : System.out.println(5/2)Integer division special feature
++  : increase by one unit-- : decrease by one unita = 5; b = a++; //post-increment : assign  increaseb = a--; //pre-increment : assign  decreaseb = ++a;b = --a;Increment Decrement Operator
Exercise
Generate a booleanresultThey evaluate the relationship between the values of the operandsA relational expression produces true if the relationship is true, and false if the relationship is untrueless 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 valuesTry out the relational operators one by oneSystem.out.println(a>b);Check out equivalence with ObjectsInteger n1 = new Integer(47); 		Integer n2 = new Integer(47); System.out.println(n1 == n2); System.out.println(n1 != n2);Equivalence Compare object references not valuesOverride equals method that exist with all objects
Works on boolean operandsLogical 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)!ALogical Operators
Continue from relational operator exercise and declare two more int variablesNow try &&, || and !Exercise
Expression will be evaluated only until the truth or falsehood of the entire expression can be unambiguously determinedThe latter parts of a logical expression might not be evaluatedShort circuit
public class ShortCircuit { 	static boolean test1(intval) { s.o.p("result: " + (val < 1)); 		return val < 1; 	} 	static boolean test2(intval) { s.o.p("result: " + (val < 2)); 	return val < 2; 	} 	static boolean test3(intval) { s.o.p("result: " + (val < 3)); 		return val < 3; 	} 	public static void main(String[] args) { booleanb = test1(0) && test2(2) && test3(2); s.o.p("expression is " + b); 	} }Short circuit blow-up
One special usage of an operator in JavaThe + and += operators can be used to concatenate stringsOperator overloadingString a = “AIR”; String b = “INDIA”System.out.println(a + b);int c = 747System.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-elseboolean-exp ? value0 : value1If 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 moldAutomatically change one type of data into another when appropriateif you assign an integral value to a floating point variable, the compiler will automatically convert the int to a floatCasting 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
inti = 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 codeIn 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.Mathprint("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 castand take care of data lossIn 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

05 operators

  • 1.
  • 2.
    What is anoperator?PrecedenceAssignment operatorMathematical operatorsIncrement & Decrement operatorRelational operatorsLogical operatorTernary operatorString operatorCasting operatorAgenda
  • 3.
    Symbol representing anoperation – mathematical, character etcNeeds one or more operands to produce resultA + B 10 + 20 Operator can produce resultOperator can change the value of the operand (side effect)Operators, operands and parenthesis combine to form expressionsWhat is an operator?
  • 4.
    Mostly mathematicalBinary –takes two arguments: +,-,*,/Unary – takes one argument: -,!Boolean operators: !String: +Bitwise & Shift: Left outsWork mostly with primitivesSome operators work with objects too =,==Java operators
  • 5.
    Defines how anexpression evaluates when several operators are presentJava 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
  • 6.
    public class Precedence{ public static void main(String[] args) { intx = 1, y = 2, z = 3; inta = 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
  • 7.
    =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
  • 8.
    + , -, * , / , %Operate and assign+= ,-=,*=,/=,%Unary operators- (inverts the sign on the operand),+ (useless)x = -a; x = a * (-b); Mathematical Operators
  • 9.
  • 10.
    Write a Javaprogram to declare to int variables and assign them literal valuesPerform different mathematical operations and assign the values to result variablesPrint the operands and resultsPrint : System.out.println(5/2)Integer division special feature
  • 11.
    ++ :increase by one unit-- : decrease by one unita = 5; b = a++; //post-increment : assign  increaseb = a--; //pre-increment : assign  decreaseb = ++a;b = --a;Increment Decrement Operator
  • 12.
  • 13.
    Generate a booleanresultTheyevaluate the relationship between the values of the operandsA relational expression produces true if the relationship is true, and false if the relationship is untrueless than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equivalent (==) and not equivalent (!=)Relational Operators
  • 14.
  • 15.
    Write a simpleJava program and declare two int variables.Assign them valuesTry out the relational operators one by oneSystem.out.println(a>b);Check out equivalence with ObjectsInteger n1 = new Integer(47); Integer n2 = new Integer(47); System.out.println(n1 == n2); System.out.println(n1 != n2);Equivalence Compare object references not valuesOverride equals method that exist with all objects
  • 16.
    Works on booleanoperandsLogical 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)!ALogical Operators
  • 17.
    Continue from relationaloperator exercise and declare two more int variablesNow try &&, || and !Exercise
  • 18.
    Expression will beevaluated only until the truth or falsehood of the entire expression can be unambiguously determinedThe latter parts of a logical expression might not be evaluatedShort circuit
  • 19.
    public class ShortCircuit{ static boolean test1(intval) { s.o.p("result: " + (val < 1)); return val < 1; } static boolean test2(intval) { s.o.p("result: " + (val < 2)); return val < 2; } static boolean test3(intval) { s.o.p("result: " + (val < 3)); return val < 3; } public static void main(String[] args) { booleanb = test1(0) && test2(2) && test3(2); s.o.p("expression is " + b); } }Short circuit blow-up
  • 20.
    One special usageof an operator in JavaThe + and += operators can be used to concatenate stringsOperator overloadingString a = “AIR”; String b = “INDIA”System.out.println(a + b);int c = 747System.out.println(a + b + c);String Operators
  • 21.
    Conditional operator, isunusual because it has three operands. It is truly an operator because it produces a value, unlike the ordinary if-elseboolean-exp ? value0 : value1If 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
  • 22.
    int a =5;int b = 6;int c = (a > b) ? a : b ; Try out ternary operator
  • 23.
    Casting into amoldAutomatically change one type of data into another when appropriateif you assign an integral value to a floating point variable, the compiler will automatically convert the int to a floatCasting 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
  • 24.
    inti = 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
  • 25.
    It’s possible toperform 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 codeIn 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
  • 26.
    If you castfrom 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.Mathprint("Math.round(above): " + Math.round(above)); print("Math.round(below): " + Math.round(below)); print("Math.round(fabove): " + Math.round(fabove)); Truncation & Rounding
  • 27.
    If you performany 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 castand take care of data lossIn 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
  • 28.