Operators

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 41

CSE310: Programming in Java

Topic: Operators in Java


Outlines
• Introduction
• Assignment Operator
• Arithmetic Operator
• Relational Operator
• Unary Operator
• Increment and Decrement Operator
• Boolean Logical Operator
• Conditional (?) Operator
• Bitwise Operator
• Operator Precedence
Introduction

 Operators are special symbols that perform specific


operations on one, two, or three operands, and then
return a result.
Assignment Operator
 One of the most common operators is the simple
assignment operator "=".
 This operator assigns the value on its right to the
operand on its left.
Example:
int salry = 25000; double speed = 20.5;

 This operator can also be used on objects to assign


object references.
Student s = new Student();
Student s2 = s;
Compound Assignments
 Arithmetic operators are combined with the simple
assignment operator to create compound assignments.

 Compound assignment operators are +=, -=, *=, /=,


%=

 For example, x+=1; and x=x+1; both increment the


value of x by 1.
Arithmetic Operators
 Java provides operators that perform addition, subtraction,
multiplication, and division.
Operator Description
Additive operator (also used for String
+ concatenation)

- Subtraction operator

* Multiplication operator

/ Division operator

% Remainder operator
Relational Operators

 Relational operators determine if one operand is


greater than, less than, equal to, or not equal to
another operand.

 It always returns boolean value i.e true or false.


Relational Operators
Operator Description

== equal to

!= not equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to


Unary Operators
 The unary operators require only one operand.
Operator Description

+ Unary plus operator; indicates positive value

- Unary minus operator; negates an expression

++ Increment operator; increments a value by 1

-- Decrement operator; decrements a value by 1

Logical complement operator; inverts the value of a


! boolean
Increment and Decrement
The ++ and the – – are Java’s increment and
decrement operators. The increment operator
increases its operand by one. The decrement
operator decreases its operand by one.
x = x + 1; // x++; post
// ++x; pre
x = x - 1; // x--; post
// --x; pre
Output?
public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=10;  
System.out.println(a++ + ++a);  
System.out.println(b++ + b++);
  
}}  
Boolean Logical Operators
 The Boolean logical operators shown here operate only
on boolean operands.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
== Equal to
!= Not equal to
?: Ternary if-then-else
public class OperatorExample{  
public static void main(String args[])
{  
int a=10;  
int b=-10;  
boolean c=true;  
boolean d=false;  
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);  
System.out.println(!d);
} }  
• The following table shows the effect of each logical
operation:

A B A|B A&B A^B ~A

False False False False False True

True False True False True False

False True True False True True

True True True True False False


public class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
System.out.println(a+b);   
System.out.println(a-b);   
System.out.println(a*b);   
System.out.println(a/b);   
System.out.println(a%b);
}}
Short-Circuit Logical Operators
• These are secondary versions of the Boolean AND and OR
operators, and are known as short-circuit logical operators.

• OR operator results in true when A is true , no matter what


B is. Similarly, AND operator results in false when A is
false, no matter what B is.

• If we use the || and && forms, rather than the | and & forms
of these operators, Java will not bother to evaluate the right-
hand operand when the outcome of the expression can be
determined by the left operand alone.
 This is very useful when the right-hand operand depends
on the value of the left one in order to function properly.

 For example
if (denom != 0 && num / denom > 10)

 The following code fragment shows how you can take


advantage of short-circuit logical evaluation to be sure
that a division operation will be valid before evaluating it.
instanceof operator
The instanceof the operator is used for type
checking. It can be used to test if an object is
an instance of a class, a subclass, or an
interface.

General format- 
object instanceof class/subclass/interface
class Simple1{  
 public static void main(String args[]){  
 Simple1 s=new Simple1();  
 System.out.println(s instanceof Simple1);   
 }  
}  
class Animal{}  
class Dog1 extends Animal{
//Dog inherits Animal  
 public static void main(String args[]){  
 Dog1 d=new Dog1();  
 System.out.println(d instanceof Animal);  
 }  
}  
class Dog2{  
 public static void main(String args[]){  
  Dog2 d=null;  
  System.out.println(d instanceof Dog2);  
 }  
}  
class Operators
{
public static void main(String[] args)
{
Person obj1 = new Person();
Person obj2 = new Boy();
System.out.println("obj1 instanceof Person: " + (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy: " + (obj1 instanceof Boy));
System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof
MyInterface));
System.out.println("obj2 instanceof Person: " + (obj2 instanceof Person));
System.out.println("obj2 instanceof Boy: " + (obj2 instanceof Boy));
System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof
MyInterface));
}}
class Person { }
class Boy extends Person implements MyInterface { }
interface MyInterface { }
Programs in java
• Calculator Program
• Factorial Program
• Palindrome Program
• String reverse
The Conditional Operator (?:)
• Java includes a special ternary (three-way)operator, ?, that can
replace certain types of if-then-else statements.
• The ? has this general form:
expression1 ? expression2 : expression3
• Here,expression1 can be any expression that evaluates to a
boolean value.

• If expression1 is true , then expression2 is evaluated; otherwise,


expression3 is evaluated.

• Both expression2 and expression3 are required to return the same


type, which can’t be void.
class Max_Two
{
public static void main(String args[])
{
int n1 = 15, n2 = 10, max;
max = (n1 > n2) ? n1 : n2;
System.out.println("Largest number :" +
max);
}
}
class EvenOddNumber
{
public static void main( String args[] )
{
int n = 3;
String msg =(n%2==0) ?" Even!" :
"Odd!";
System.out.println(msg);
}
}
Bitwise Operators
These operators act upon the individual bits of their
operands.

Can be applied to the integer types, long, int, short, char,


and byte.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
Bitwise Logical Operators
• The bitwise logical operators are
• ~ (NOT)
• & (AND)
• | (OR)
• ^ (XOR)


The Left Shift Operator
The decimal representation of a number is a
base-10 number system having only ten states 0,
1, 2, 3, 4, 5, 6, 7, 8, and 9. For example, 4, 10,
16, etc.

The Binary representation of a number is a base-


2 number system having only two states 0 and 1.
For example, the binary representation of 4, a
base-9 decimal number system is given by 100,
10 as 1010, 16 as 1000, etc.
Note: Left shifting a number by certain positions
is equivalent to multiplying the number by
two raised to the power of the specified
positions. That is,
left shift x by n positions <=> x * 2n
• The left shift operator,<<, shifts all of the bits in a value
to the left a specified number of times.
value << num

• Example:
01000001 65 << 2
00000100 4
The Right Shift Operator
• The right shift operator, >>, shifts all of the bits in a value
to the right a specified number of times.
value >> num
• It is also known as signed right shift.

• Example:
00100011 35 >> 2
00001000 8
• When we are shifting right, the top (leftmost) bits exposed
by the right shift are filled in with the previous contents of
the top bit.

• This is called sign extension and serves to preserve the


sign of negative numbers when you shift them right.
The Unsigned Right Shift
• In these cases, to shift a zero into the high-order bit no
matter what its initial value was. This is known as an
unsigned shift.

• To accomplish this, we will use Java’s unsigned, shift-right


operator, >>>, which always shifts zeros into the high-order
bit.

• Example:
– 11111111 11111111 11111111 11111111 –1 in
binary as an int
– >>>24
– 00000000 00000000 00000000 11111111 255 in
binary as an int
Operator Precedence
Brainstorming 1
What will be the output of the following code snippets?

 byte b = 30; System.out.println(~b);

 byte b = -53; System.out.println(~b);

 System.out.println(34>>3);

 System.out.println(-34>>3);

 System.out.println(-34>>>3);
Brainstorming 2

int x = 10, y = 5;
while(x- - > 7 || + + y < 8 );
System.out.print(x);
System.out.print(y);

A. 95
B. 67
C. 78
D. 48
E. 77
F. N.O.T
Brainstorming 3
System.out.print(2>1||4>3?false:true);
class X{}
class Y extends X{}
class Z extends Y{}

X x1 = new Y();
Y y1 = new Z();
Y y2 = new Y();
System.out.println( x1 instanceof X);
System.out.println( x1 instanceof Z);
System.out.println( y1 instanceof Z);
System.out.println( y2 instanceof X);
Brainstorming 4

System.out.print(2>1||4>3?false:true);

You might also like