0% found this document useful (0 votes)
11 views

Operators

The document discusses various operators in Java including arithmetic, bitwise, relational, logical, shift, assignment, and ternary operators. It provides examples of how to use each operator type and explains what each operator does.

Uploaded by

Priyanshu Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Operators

The document discusses various operators in Java including arithmetic, bitwise, relational, logical, shift, assignment, and ternary operators. It provides examples of how to use each operator type and explains what each operator does.

Uploaded by

Priyanshu Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Operators

• Java provides a rich operator environment. Most


of its operators can be divided into the following
four groups:
– arithmetic,
– bitwise,
– relational, and
– logical.
• Java also defines some additional operators that
handle certain special situations.
Arithmetic Operators
The operands of the
arithmetic operators
must be of a numeric
type.
You cannot use
them on boolean types,
but you can use them
on char types, since the
char type in Java is,
essentially, a subset of
int.
// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {

// arithmetic using integers


System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3; // arithmetic using doubles
int c = b / 4; System.out.println("\nFloating Point
int d = c - a; Arithmetic");
int e = -d; double da = 1 + 1;
System.out.println("a = " + a); double db = da * 3;
System.out.println("b = " + b); double dc = db / 4;
System.out.println("c = " + c); double dd = dc - a;
System.out.println("d = " + d); double de = -dd;
System.out.println("e = " + e); System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
• The Modulus Operator (%)
• Arithmetic Compound Assignment Operators (+=)
• Increment and Decrement (++, --)

public class IncOp


{
public static void main(String args[])
{
int x=1;
int r = --x + x++ + ++x + x--;
//x=[0121]r=[0+0+2+2]
System.out.println(x + " " + r);
}
//Guess the output
public class Test {
public static void main(String[] args)
{
int a = 10;
int b = ++(++a);
System.out.println(b);
}
}
//final variable
public class Test {
public static void main(String[] args)
{
final int a = 10;
int b = ++a;
System.out.println(b);
}
}
// Can not be applied boolean data type
public class Test {
public static void main(String[] args)
{
boolean b = false;
b++;
System.out.println(b);
}
}
The Bitwise Operators
• Java defines several bitwise operators that can be applied to
the integer types, long, int, short, char, and byte.
• These operators act upon the individual bits of their
operands.
The Bitwise Operators
• The byte value for 42 in binary is 00101010, where
each position represents a power of two, starting with
20 at the rightmost bit.
• All of the integer types (except char) are signed
integers. This means that they can represent negative
values as well as positive ones.
• Java uses an encoding known as two’s complement,
which means that negative numbers are represented
by inverting (changing 1’s to 0’s and vice versa) all of
the bits in a value, then adding 1 to the result.
• Example, –42 is represented by inverting all of the bits
in 42, or 00101010, which yields 11010101, then
adding 1, which results in 11010110, or –42.
Bitwise OR (|) –
This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input values,
i.e, if either of the bits is 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111

0111 = 7 (In decimal)

Bitwise AND (&) –


This operator is binary operator, denoted by ‘&’. It returns bit by bit AND of input values, i.e,
if both bits are 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111

0101 = 5 (In decimal)


Bitwise XOR (^) –
This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input
values, i.e, if corresponding bits are different, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111

0010 = 2 (In decimal)

Bitwise Complement (~) –


This operator is unary operator, denoted by ‘~’. It returns the one’s compliment
representation of the input value, i.e, with all bits inversed, means it makes every 0 to 1,
and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)
Bitwise Compliment Operation of 5

~ 0101

1010 = 10 (In decimal)


public class Bitoperators {
public static void main(String[] args) {
int a = 5;
int b = 7;
// bitwise and
System.out.println("a&b = " + (a & b));
// bitwise or
System.out.println("a|b = " + (a | b));
// bitwise xor
System.out.println("a^b = " + (a ^ b));
// bitwise not ~0101=1010
// will give 2's complement of 1010 = -6
System.out.println("~a = " + ~a); Output :
a&b = 5
// assignment a=a&b
a|b = 7
a &= b; a^b = 2
System.out.println("a= " + a); ~a = -6
} a= 5
}
Shift Operators
• These operators are used to shift the bits of a
number left or right thereby multiplying or
dividing the number by two respectively.
• They can be used when we have to multiply or
divide a number by two.
• Syntax
number shift_op number_of_shift;
• Signed Right shift operator (>>)
• Unsigned Right shift operator (>>>)
• Left shift operator (<<)
public class Shiftoperators {
public static void main(String[] args)
{
int a = 5;
int b = -10;

// left shift operator


// 0000 0101<<2 =0001 0100 (20)
// similar to 5*(2^2)
System.out.println("a<<2 = " + (a << 2));

// right shift operator


// 0000 0101 >> 2 =0000 0001 (1)
// similar to 5/(2^2)
System.out.println("b>>2 = " + (b >> 2));

// unsigned right shift operator


System.out.println("b>>>2 = " + (b >>> 2)); Output :
} a<<2 = 20
} b>>2 = -3
b>>>2 = 1073741821
Relational Operators

The outcome of these operations is a boolean value.


Boolean Logical Operators
Short-Circuit Logical Operators
• Java provides two interesting Boolean operators,
These are secondary versions of the Boolean AND and
OR operators, and are known as short-circuit logical
operators.
• The OR operator results in true when A is true, no
matter what B is. Similarly, the AND operator results
in false when A is false, no matter what B is.
• If you 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.
Short-Circuit Logical Operators
• if (denom != 0 && num / denom > 10)
• Since the short-circuit form of AND (&&) is used,
there is no risk of causing a run-time exception
when denom is zero.
• If this line of code were written using the single &
version of AND, both sides would be evaluated,
causing a run-time exception when denom is zero.
import java.io.*;
import java.util.Scanner;
public class AndopEx
{
public static void main(String[] args)
{
int x, y;
int sum=0;
Scanner sobj = new Scanner(System.in);

System.out.println("Enter x & y vals: ") ;


x = sobj.nextInt();
y = sobj.nextInt();

if(x>0 && ++y>0)


sum = x+y;

System.out.println("x=" + x + " and y=" + y + "\nx+y=" + sum);


}
}
The Assignment Operator
var = expression;
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
• This fragment sets the variables x, y, and z to 100
using a single statement.
• This works because the = is an operator that yields
the value of the right-hand expression.
• Thus, the value of z = 100 is 100, which is then
assigned to y, which in turn is assigned to x.
• Using a “chain of assignment” is an easy way to set
a group of variables to a common value.
The ? Operator
• Java includes a special ternary (three-way)
operator that can replace certain types of if-then-
else statements. This operator is the ?.
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. The result of the ?
operation is that of the expression evaluated. Both
expression2 and expression3 are required to return
the same type, which can’t be void.
k = i < 0 ? -i : i; // get absolute value of i
public class TernaryEx
{
public static void main(String[] args)
{
int A = 10;
int B = 20;
String result = A> B ? "A is greater" : "B is greater";
System.out.println(result);
}
}

For three variables:


String result = a > b ? a > c ? "a is greatest" : "c is greatest" : b > c ? "b is greatest" : "c is greatest“;
Operator Precedence
• Java conditions
• enum
Java’s Selection Statements

• if
• if-else
• if-else-if ladder
• nested if
• switch
• Java’s program control statements can be put into
the following categories:
– Selection
• Selection statements allow your program to choose
different paths of execution based upon the outcome of an
expression or the state of a variable.
– Iteration
• Iteration statements enable program execution to repeat
one or more statements (that is, iteration statements form
loops).
– jump
• Jump statements allow your program to execute in a
nonlinear fashion.
Control Statements
• The if Statement : The Java if
statement tests the condition.
• It executes the if block if
condition is true.

if(condition) {
// statement;
}

if(num < 100)


System.out.println(“less than 100");
//Java Program to demonstrate the use of if statement.

public class IfExample {


public static void main(String[] args) {
//defining an 'age' variable
int age=20;

//checking the age


if(age>18){
System.out.print(“Eligible for voting");
}
}
}
if - else
• The Java if-else statement also tests the condition.
• It executes the if block if condition is true
otherwise else block is executed.

Syntax:
if(condition){
//code if condition is true
}
else{
//code if condition is false
}
//It is a program of odd and even number.

public class IfElseExample {


public static void main(String[] args) {
int number=13;

//Check if the number is divisible by 2 or not


if(number%2==0){
System.out.println("even number");
}
else{
System.out.println("odd number");
}
}
}
//A year is leap, if it is divisible by 4 and 400. But, not by 100.

public class LeapYearEx {


public static void main(String[] args) {
int year=2020;

if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0))


{
System.out.println("LEAP YEAR");
}
else
{
System.out.println("COMMON YEAR");
}
}
}
if-else-if ladder
• The if-else-if ladder statement executes one
condition from multiple statements.
Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...

else{
//code to be executed if all the conditions are false

}
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.

public class IfElseIfExample {


public static void main(String[] args) {
int marks=65;

if(marks<35){
System.out.println("fail");
}
else if(marks>=35 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
//Find out given no is +ve or –ve or zero

public class PositiveNegativeExample {


public static void main(String[] args) {
int number=-13;

if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
Nested if
• The nested if statement represents
the if block within another if block.
• Here, the inner if block condition
executes only when outer if block
condition is true.

Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
//Java Program to demonstrate the use of Nested If Statement.

public class JavaNestedIfExample {


public static void main(String[] args) {
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
else{
System.out.println("You are not eligible to donate blood");
}
}
else{
System.out.println("Age must be greater than 18");
}
}
}
Switch Statement
• The Java switch statement executes one statement from multiple
conditions.
• It is like if-else-if ladder statement.
• The switch statement works with byte, short, int, long, enum
types, String and some wrapper types like Byte, Short, Int, and
Long.
• There can be one or N number of case values for a switch
expression.
• The case value must be of switch expression type only. The case
value must be literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it
renders compile-time error.
• Each case statement can have a break statement which is
optional. When control reaches to the break statement, it jumps
the control after the switch expression. If a break statement is
not found, it executes the next case.
• The case value can have a default label which is optional.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are
not matched;
}
public class SwitchExample {
public static void main(String[] args) {
int number=2;

//Switch expression
switch(number){
//Case statements
case 1: System.out.println(“ONE");
break;
case 2: System.out.println(“TWO");
break;
case 3: System.out.println(“THREE");
break;
//Default case statement
default:System.out.println("Not in 1, 2 or 3");
}
}
}
case 5: monthString="5 - May";
//Name of the month break;
case 6: monthString="6 - June";
public class SwitchMonthExample { break;
public static void main(String[] args) { case 7: monthString="7 - July";
//Specifying month number break;
int month=7; case 8: monthString="8 - August";
String monthString=""; break;
case 9: monthString="9 - September";
//Switch statement break;
switch(month){ case 10: monthString="10 - October";
//case statements within the switch block break;
case 11: monthString="11 - November";
case 1: monthString="1 - January"; break;
break; case 12: monthString="12 - December";
case 2: monthString="2 - February"; break;
break;
case 3: monthString="3 - March"; default:System.out.println("Invalid Month!");
break;
case 4: monthString="4 - April"; }
break; //Printing month of the given number
System.out.println(monthString);
}
}
switch w/o break
• It executes all statements after the first match, if a
break statement is not present.
//without break statement
public class SwitchExample2 {
public static void main(String[] args) {
int num=2;
//switch expression with int value
switch(num){
//switch cases without break statements
Output:
case 1: System.out.println(“1");
2
case 2: System.out.println(“2"); 3
case 3: System.out.println(“3"); Not in 1, 2 or 3
default:System.out.println("Not in 1, 2 or 3");
}
}
}
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1: OUTPUT:
case 2: i is less than 5
case 3: i is less than 5
case 4: i is less than 5
System.out.println("i is less than 5"); i is less than 5
break; i is less than 5
case 5: i is less than 10
case 6: i is less than 10
case 7: i is less than 10
case 8: i is less than 10
case 9: i is less than 10
System.out.println("i is less than 10"); i is 10 or more
break; i is 10 or more
default:
System.out.println("i is 10 or more");
}
}
}
Nested Switch Statement
• We can use switch statement inside other switch
statement in Java.
• It is known as nested switch statement.
switch(expression1){
case value1:
//code to be executed;
break;
case value2:
switch(expression2){
case value21:
//code to be executed;
break; //optional
case value22:
break; //optional
default:
default code to be executed
}
break;
default:
code to be executed if all cases are not matched;
}
Example: -
You are searching for a department in a university and you’re asked to select a
school from a choice of three schools namely:
1. School of Arts
2. School of Business
3. School of Engineering
Having selected a school you are again provided with a list of departments that fall
under the department namely:
1. School of Arts
A. Department of finearts
B. Department of sketcharts
2. School of Business
A. Department of Commerce
B. Department of purchasing
3. School of Engineering
A. CSE
B. ECE
The initial choices for Computer Science, Business and Engineering schools would
be inside as a set of switch statements. Then various departments would then be
listed within inner switch statements beneath their respective schools.
import java.io.*;
import java.util.Scanner;

class NestedExample
{
public static void main(String args[])
{
int a,b;
System.out.println("1.School of Arts\n");
System.out.println("2.School of Business\n");
System.out.println("3.School of Engineering\n");
System.out.println("make your selection\n");
Scanner sobj = new Scanner(System.in);
a=sobj.nextInt();
switch (a)
{
case 1:
System.out.println("You chose Arts\n" ); break;
case 2:
System.out.println("You chose Business\n" ); break;
case 3:
// Engineering
System.out.println("You chose Engineering\n" );
System.out.println("1.CSE\n" );
System.out.println("2.ECE\n" );
System.out.println("make your selection\n");
b=sobj.nextInt();
switch(b)
{
case 1:
System.out.println("You chose CSE\n" );
break;
case 2:
System.out.println("You chose ECE" );
break;
}
break;
}
}
}
enum in Switch Statement
• Java allows us to use enum in switch statement.
• An enum is a special "class" that represents a group
of constants (unchangeable variables, like final variables).
• To create an enum, use the enum keyword (instead of
class or interface), and separate the constants with a
comma.
• Note that they should be in uppercase letters:
enum Level {
LOW, MEDIUM, HIGH
}

You can access enum constants with the dot syntax:

Level myVar = Level.MEDIUM;


enum in Switch Statement
public class JavaSwitchEnumExample {
public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
case Wed:
public static void main(String args[])
System.out.println("Wednesday");
{
break;
Day[] DayNow = Day.values();
case Thu:
for (Day Now : DayNow)
System.out.println("Thursday");
{
break;
switch (Now)
case Fri:
{
System.out.println("Friday");
case Sun:
break;
System.out.println("Sunday");
case Sat:
break;
System.out.println("Saturday");
case Mon:
break;
System.out.println("Monday");
}
break;
}
case Tue:
}
System.out.println("Tuesday");
}
break;
Output:
Sunday
Monday
Twesday
Wednesday
Thursday
Friday
Saturday

You might also like