SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Operators DhrubojyotiKayal
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) {  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 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 booleanresult 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(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 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
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 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 castand 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

Weitere ähnliche Inhalte

Was ist angesagt? (19)

operators in c++
operators in c++operators in c++
operators in c++
 
C Prog. - Operators and Expressions
C Prog. - Operators and ExpressionsC Prog. - Operators and Expressions
C Prog. - Operators and Expressions
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Java 2
Java 2Java 2
Java 2
 
Operators in c++
Operators in c++Operators in c++
Operators in c++
 
Report on c
Report on cReport on c
Report on c
 
Operators and expressions
Operators and expressionsOperators and expressions
Operators and expressions
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
 
Arithmetic operator
Arithmetic operatorArithmetic operator
Arithmetic operator
 
Operator.ppt
Operator.pptOperator.ppt
Operator.ppt
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Oop using JAVA
Oop using JAVAOop using JAVA
Oop using JAVA
 
operators in c++
operators in c++operators in c++
operators in c++
 
Operators
OperatorsOperators
Operators
 
C++
C++ C++
C++
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
C# operators
C# operatorsC# operators
C# operators
 
Chapter 5 - Operators in C++
Chapter 5 - Operators in C++Chapter 5 - Operators in C++
Chapter 5 - Operators in C++
 

Andere mochten auch

B ulgarian potatoes_2003 - final
B ulgarian potatoes_2003 - finalB ulgarian potatoes_2003 - final
B ulgarian potatoes_2003 - finalVesela Ruseva
 
Cvetelina 9a pollution in bulgaria
Cvetelina 9a pollution in bulgariaCvetelina 9a pollution in bulgaria
Cvetelina 9a pollution in bulgariaVesela Ruseva
 
Natural disasters final
Natural disasters finalNatural disasters final
Natural disasters finalVesela Ruseva
 
Measures taken by local autorities
Measures taken by local autoritiesMeasures taken by local autorities
Measures taken by local autoritiesVesela Ruseva
 
Life by the water presentation first meeting
Life by the water presentation  first meetingLife by the water presentation  first meeting
Life by the water presentation first meetingVesela Ruseva
 
Water sports in bulgaria
Water sports in bulgariaWater sports in bulgaria
Water sports in bulgariaVesela Ruseva
 
1 java - data type
1  java - data type1  java - data type
1 java - data typevinay arora
 
V Gatti Samples
V Gatti SamplesV Gatti Samples
V Gatti Samplesguest3f18a
 
христофор колумб Hyusein
христофор колумб   Hyuseinхристофор колумб   Hyusein
христофор колумб HyuseinVesela Ruseva
 
Water plants and animals
Water plants and animalsWater plants and animals
Water plants and animalsVesela Ruseva
 
Water sports nevelina
Water sports nevelinaWater sports nevelina
Water sports nevelinaVesela Ruseva
 

Andere mochten auch (20)

Data type2 c
Data type2 cData type2 c
Data type2 c
 
B ulgarian potatoes_2003 - final
B ulgarian potatoes_2003 - finalB ulgarian potatoes_2003 - final
B ulgarian potatoes_2003 - final
 
18 concurrency
18   concurrency18   concurrency
18 concurrency
 
Cvetelina 9a pollution in bulgaria
Cvetelina 9a pollution in bulgariaCvetelina 9a pollution in bulgaria
Cvetelina 9a pollution in bulgaria
 
Natural disasters final
Natural disasters finalNatural disasters final
Natural disasters final
 
Water plants rosi
Water plants rosiWater plants rosi
Water plants rosi
 
Measures taken by local autorities
Measures taken by local autoritiesMeasures taken by local autorities
Measures taken by local autorities
 
Pollution of burgas
Pollution of burgasPollution of burgas
Pollution of burgas
 
Life by the water presentation first meeting
Life by the water presentation  first meetingLife by the water presentation  first meeting
Life by the water presentation first meeting
 
Water sports in bulgaria
Water sports in bulgariaWater sports in bulgaria
Water sports in bulgaria
 
C language basics
C language basicsC language basics
C language basics
 
1 java - data type
1  java - data type1  java - data type
1 java - data type
 
Colonial spices
Colonial spicesColonial spices
Colonial spices
 
V Gatti Samples
V Gatti SamplesV Gatti Samples
V Gatti Samples
 
Java operators
Java operatorsJava operators
Java operators
 
христофор колумб Hyusein
христофор колумб   Hyuseinхристофор колумб   Hyusein
христофор колумб Hyusein
 
Water plants and animals
Water plants and animalsWater plants and animals
Water plants and animals
 
Atanasov lake
Atanasov lakeAtanasov lake
Atanasov lake
 
Waterinaytos
WaterinaytosWaterinaytos
Waterinaytos
 
Water sports nevelina
Water sports nevelinaWater sports nevelina
Water sports nevelina
 

Ähnlich wie 05 operators

Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++Neeru Mittal
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)jahanullah
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsDhivyaSubramaniyam
 
Operators
OperatorsOperators
OperatorsKamran
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_castsAbed Bukhari
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)It Academy
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and StringsIt Academy
 
Programming presentation
Programming presentationProgramming presentation
Programming presentationFiaz Khokhar
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and StringsIt Academy
 
Few Operator used in c++
Few Operator used in c++Few Operator used in c++
Few Operator used in c++sunny khan
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tourSwarup Boro
 

Ähnlich wie 05 operators (20)

Operators and expressions in C++
Operators and expressions in C++Operators and expressions in C++
Operators and expressions in C++
 
Operators
OperatorsOperators
Operators
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Operators
OperatorsOperators
Operators
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)chap 2 : Operators and Assignments (scjp/ocjp)
chap 2 : Operators and Assignments (scjp/ocjp)
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
 
Few Operator used in c++
Few Operator used in c++Few Operator used in c++
Few Operator used in c++
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
C++ revision tour
C++ revision tourC++ revision tour
C++ revision tour
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
 
Py-Slides-2 (1).ppt
Py-Slides-2 (1).pptPy-Slides-2 (1).ppt
Py-Slides-2 (1).ppt
 
Py-Slides-2.ppt
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.ppt
 

Mehr von dhrubo kayal

01 session tracking
01   session tracking01   session tracking
01 session trackingdhrubo kayal
 
03 handling requests
03 handling requests03 handling requests
03 handling requestsdhrubo kayal
 
02 up close with servlets
02 up close with servlets02 up close with servlets
02 up close with servletsdhrubo kayal
 
01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setupdhrubo kayal
 
14 initialization & cleanup
14   initialization & cleanup14   initialization & cleanup
14 initialization & cleanupdhrubo kayal
 
08 class and object
08   class and object08   class and object
08 class and objectdhrubo kayal
 
04 data types & variables
04   data types & variables04   data types & variables
04 data types & variablesdhrubo kayal
 
03 hello world with java
03   hello world with java03   hello world with java
03 hello world with javadhrubo kayal
 

Mehr von dhrubo kayal (20)

Cipla 20-09-2010
Cipla   20-09-2010Cipla   20-09-2010
Cipla 20-09-2010
 
01 session tracking
01   session tracking01   session tracking
01 session tracking
 
03 handling requests
03 handling requests03 handling requests
03 handling requests
 
02 up close with servlets
02 up close with servlets02 up close with servlets
02 up close with servlets
 
01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup01 overview-servlets-and-environment-setup
01 overview-servlets-and-environment-setup
 
19 reflection
19   reflection19   reflection
19 reflection
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
16 containers
16   containers16   containers
16 containers
 
15 interfaces
15   interfaces15   interfaces
15 interfaces
 
14 initialization & cleanup
14   initialization & cleanup14   initialization & cleanup
14 initialization & cleanup
 
13 inheritance
13   inheritance13   inheritance
13 inheritance
 
12 encapsulation
12   encapsulation12   encapsulation
12 encapsulation
 
11 static
11   static11   static
11 static
 
10 access control
10   access control10   access control
10 access control
 
09 packages
09   packages09   packages
09 packages
 
08 class and object
08   class and object08   class and object
08 class and object
 
07 flow control
07   flow control07   flow control
07 flow control
 
04 data types & variables
04   data types & variables04   data types & variables
04 data types & variables
 
03 hello world with java
03   hello world with java03   hello world with java
03 hello world with java
 
02 what is java
02   what is java02   what is java
02 what is java
 

05 operators

  • 2. What is an operator? Precedence Assignment operator Mathematical operators Increment & Decrement operator Relational operators Logical operator Ternary operator String operator Casting operator Agenda
  • 3. 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?
  • 4. 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
  • 5. 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
  • 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
  • 10. 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
  • 11. ++ : 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
  • 13. Generate a booleanresult 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
  • 15. 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
  • 16. 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
  • 17. Continue from relational operator exercise and declare two more int variables Now try &&, || and ! Exercise
  • 18. 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
  • 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 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
  • 21. 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
  • 22. int a = 5; int b = 6; int c = (a > b) ? a : b ; Try out ternary operator
  • 23. 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
  • 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 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
  • 26. 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
  • 27. 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 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
  • 28. Q&A