0% found this document useful (0 votes)
236 views44 pages

Operators and Control Statements in Java

Operators are used to perform operations on variables and values in Java. The main types of operators include arithmetic, relational, logical, assignment, bitwise, and unary operators. Arithmetic operators perform basic math operations like addition, subtraction, multiplication, and division. Relational operators compare values. Logical operators check true/false conditions. Assignment operators assign values. Bitwise operators perform operations on individual bits and unary operators operate on a single operand.

Uploaded by

honaday945
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
236 views44 pages

Operators and Control Statements in Java

Operators are used to perform operations on variables and values in Java. The main types of operators include arithmetic, relational, logical, assignment, bitwise, and unary operators. Arithmetic operators perform basic math operations like addition, subtraction, multiplication, and division. Relational operators compare values. Logical operators check true/false conditions. Assignment operators assign values. Bitwise operators perform operations on individual bits and unary operators operate on a single operand.

Uploaded by

honaday945
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 44

Operators in java

Operators are used to perform operations on variables and


values.
There are many types of operators in Java which are given below:
 Arithmetic Operator,
 Relational Operator,
 Logical Operator,
 Assignment Operator,
 Bitwise Operator,
 Unary Operator,
 Shift Operator,
 Ternary Operator
1. Arithmetic Operator Java arithmetic operators are used to perform
addition, subtraction, multiplication, and division. They act as basic
mathematical operations

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

1
class Arithmatic
{
public static void main(String args[])
{
int a=10,b=20;
int c=a+b;
System.out.println("addition of a and b :"+c);
System.out.println("subtraction of a and b :"+(b-a));
c=a*b;
System.out.println("multiplication of of a and b :"+c);
System.out.println("division of a and b :"+(b/a));
System.out.println("modulo division of a and b :"+(b%a));
}
}

2
2. . Relational operators : Relational operators are used to check the
relationship between two operands. For example,

// check is a is less than b


a < b;

Here, > operator is the relational operator. It checks if a is less


than b or not.
It returns either true or false .

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true

class Relational
{

public static void main(String args[])


{
int a=10,b=20;

System.out.println("a==b :"+(a==b));
System.out.println("a<b :"+(a<b));
System.out.println("a<=b :"+(a<=b));
System.out.println("a>b :"+(a>b));

3
System.out.println("a>=b :"+(a>=b));
System.out.println("a!=b :"+(a!=b));
}
}
Output:

3. Logical operators are used to check whether an expression


is true or false . They are used in decision making.

Operator Example Meaning

&& (Logical AND) expression1 && true only if both


expression2 expression1 and expression2
are true
|| (Logical OR) expression1 || expression2 true if either expression1 or
expression2 is true
! (Logical NOT) !expression true if expression is false
and vice versa

class Logical
{

public static void main(String args[])


{
int a=10,b=20,c=30;

System.out.println("a<5 && a<=10 :"+(a<5 &&a<=10));// false


System.out.println("a<=10 && a>5:"+(a<=10 &&a>5));//true

4
System.out.println("a<1 && a<9 :"+(a<1 && a<9));//false
System.out.println("a<20 || a>7 :"+(a<20||a>7));//true
System.out.println("a>=10||c>20 :"+(a>=10 ||c>20));//true
System.out.println("c>40 || c>60 :"+(c>40|| c>60));// false
}
}
Output:

4. Java Unary Operators


Unary operators are used with only one operand. For example, ++ is a unary
operator that increases the value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:

Operator Meaning

+ Unary plus: not necessary to use since numbers are positive without using it

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

5
• Increment(++): It is used to increment the value of an integer. It can be
used in two separate ways:
• Pre-increment operator: When placed before the variable name, the
operand’s value is incremented instantly.
• Syntax:
• ++num

class Increment
{
public static void main(String args[])
{
int a,b=10;
a=++b;
System.out.println(" a= "+ a);//11
System.out.println(" b= " +b);//11
}
}

• Post-increment operator: When placed after the variable name, the


value of the operand is incremented but the previous value is retained
temporarily until the execution of this statement and it gets updated
before the execution of the next statement
• Syntax
• Num++.

class Increment
{

6
public static void main(String args[])
{
int a,b=10;
a=b++;
System.out.println(" a= "+ a);//10
System.out.println(" b= " +b);//11
}
}

• Decrement(--): It is used to decrement the value of an integer. It can be


• used in two separate ways:
• Post-decrement operator: When placed after the variable name, the value
of the operand is decremented but the previous values is retained
temporarily until the execution of this statement and it gets updated
before the execution of the next statement.
• Syntax:
• num--

class Decrement
{
public static void main(String args[])
{
int a,b=10;
a=b--;
System.out.println(" a= "+ a);//10
System.out.println(" b= " +b);//9

7
}
}

• Pre-decrement operator: When placed before the variable name, the


operand’s value is decremented instantly.
• Syntax:
• --num

5. The Assignment Operators


• Assignment operators are used to assign values to variables.
• In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
• X=10

8
Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

class Assignment
{
public static void main(String args[])
{
int a=10,b=20,c=30;
a+=b;
System.out.println("a+=b :" +a);
a-=b;
System.out.println("a-=b :" +a);
a*=10;
System.out.println("a*=10 :" +a);
a/=5;
System.out.println("a/=5 :" +a);
b%=2;
System.out.println("b%=2 :" +b);
}
}
Output:

9
6.Bitwise operators
• Bitwise operators are used to performing manipulation of individual bits
of a number. They can be used with any of the integral types (char, short,
int, etc). They are used when performing update and query operations of
Binary indexed tree.
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< Left Shift
>> Right Shift
~ Bitwise Complement

• Bitwise AND (&) –
• This operator is a 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 OR (|) –

10
• This operator is a 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 XOR (^) –
This operator is a 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 a unary operator, denoted by ‘~’. It returns the one’s
complement representation of the input value, i.e, with all bits inverted,
which means it makes every 0 to 1, and every 1 to 0.
For example,
a = 10 = 1010 (In Binary)

Bitwise Compliment Operation of 10 is -11

28 27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
1010 0 0 0 0 0 1 0 1 0
~10 1 1 1 1 1 0 1 0 1
1’s 1 0 0 0 0 1 0 1 0
complement
2’s +1
complement
1 0 0 0 0 1 0 1 1
-11
11
Bitwise Left Shift Operator (<<)
Left shift operator shifts the bits of the number towards left a specified number of
positions. The symbol for this operator is <<. When you write x<<n, the meaning is
to shift the bits of x towards left n specified positions.

Example
If x=10, then calculate x<<2 value.

Shifting the value of x towards the left two positions will make the leftmost 2 bits to
be lost. The value of x is 10. The binary representation of 10 is 00001010. The
procedure to do left shift explained in the following example:

Observe the above example, after shifting the bits to the left the binary
number 00001010 (in decimal 10) becomes 00101000 (in decimal 40).

Bitwise Right Shift Operator


The Right Shift Operator shifts the bits of the number towards right a specified n
number of positions. Right shift operator represented by the symbol >>, read as
double greater than. When you write x>>n, the meaning is to shift the
bits x towards the right n specified positions.

>> shifts the bits towards the right and also preserve the sign bit, which is the
leftmost bit. The leftmost bit represents the sign of the number. The sign
bit 0 represents a positive number, and 1 represents a negative number. So
after performing >> on a positive number, we get a positive value in the result
also. When we perform >> on a negative number, again we get a negative
value.

Example
If x=10, then calculate x>>2 value.

Shifting the value of x towards the right two positions will make the rightmost 2 bits
to be lost. The value of x is 10. The binary representation of 10 is 00001010. The
procedure to do right shift explained in the following example:

Observe the above example, after shifting the bits to the right the binary
number 00001010 (in decimal 10) becomes 00000010 (in decimal 2).

class Bitwise

public static void main(String args[])

12
int a=7,b=10;

System.out.println(" a & b= "+(a & b));

System.out.println(" a | b= "+(a | b));

System.out.println(" a ^ b= "+(a ^ b));

System.out.println(" a << 2= "+(a << 2));

System.out.println(" b >> 2= "+(a >> 2));

System.out.println(" ~a = "+( ~a ));

7.Ternary operator

The ternary operator is a part of Java’s conditional statements. As the


name ternary suggests, it is the only operator in Java consisting of three
operands.
The ternary operator can be thought of as a simplified version of the if-else
statement with a value to be returned.

13
Syntax
The three operands in a ternary operator include:
A boolean expression that evaluates to either true or false.
A value to be assigned if the expression is evaluated to true.
A value to be assigned if the expression is evaluated to false.
variable var = (booleanExpression) ? value1 if true : value2 if false
The variable var on the left-hand side of the = (assignment) operator will be
assigned:

class Terinary
{
public static void main(String args[])
{
int a=1000,b=200;
int max=(a>b)?a:b;

14
System.out.println(" maximam : "+max);
}
}

class Terinary1
{
public static void main(String args[])
{
int a=-10;
String s=(a>0)?"positive number":"negitive number";
System.out.println(" the no is : "+s);
}
}

15
What are Control Statements in Java?
 Decision Making Statements

1. Simple if statement
2. if-else statement
3. Nested if statement
4. Switch statement

 Looping statements

1. While
2. Do-while
3. For
4. For-Each

 Break
 Continue

Every programmer is familiar with the term statement, which can simply be defined as an
instruction given to the computer to perform specific operations. A control statement in java
is a statement that determines whether the other statements will be executed or not. It
controls the flow of a program. An ‘if’ statement in java determines the sequence of
execution between a set of two statements.

Control Statements can be divided into three categories, namely

16
 Selection statements
 Iteration statements
 Jump statements

Decision-Making Statements
Statements that determine which statement to execute and when are known as
decision-making statements. The flow of the execution of the program is controlled
by the control flow statement.
There are four decision-making statements available in java.

• if statement
• if-else statement
• else-if statement
• Nested if-statement
• Switch case

Simple if statement

The if statement determines whether a code should be executed based on the


specified condition.

Syntax:

if (condition) {

Statement 1; //executed if condition is true

Statement 2; //executed irrespective of the condition

17
Example 1.
class SimpleIf
{
public static void main(String args[])
{
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
}
}

18
Example explained

In the example above we use two variables, x and y, to test whether x is


greater than y (using the > operator). As x is 20, and y is 18, and we know
that 20 is greater than 18, we print to the screen that "x is greater than y".

Example 2
class SimpleIf
{
public static void main(String args[])
{
int a=101,b=102;
if(a!=b)
{
System.out.println( " a != b ");
}
}
}

19
Example 3
class SimpleIf
{
public static void main(String args[])
{
int a=10;
if(a>0)
{
System.out.println( " a is positive no ");
}
}
}

20
2.. 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.
Flowchart

if(condition)

21
{
Code to be executed if condition is true;
}
else
{
Code to be executed if condition is false;
}
Example 1
class IfElse
{
public static void main(String args[])
{
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
}
}

Example explained

In the example above, time (20) is greater than 18, so the condition
is false. Because of this, we move on to the else condition and print to the
screen "Good evening". If the time was less than 18, the program would
print "Good day".

22
Example 2

class IfElse
{
public static void main(String args[])
{
int a=10;
if(a%2==0)
{
System.out.println( a+" is Even no");
}
else
{
System.out.println( a+" is Even no");
}
}
}
Example 3
class IfElse
{
public static void main(String args[])
{
int a=13;
if(a%2==0)
{
23
System.out.println( a+" is Even no");
}
else
{
System.out.println( a+" is Even no");
}
}
}

Java if...else...if Statement


Use the else if statement to specify a new condition if the first condition
is false.

Syntax

if (condition1) {
// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and condition2 is


true

} else {

24
// block of code to be executed if the condition1 is false and condition2 is
false
}
class IfElseIf{

public static void main (String args[])


{

int time = 22;

if (time < 10) {

System.out.println("Good morning.");

} else if (time < 20) {


System.out.println("Good day.");
} else {

System.out.println("Good evening.");

// Outputs "Good evening."

25
Example explained

In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false,
so we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

class ElseIf{
public static void main(String args[]){
int i=0;
if(i>0)
{
System.out.println(i +" is greater than 0");
}
else if(i<0)
{
System.out.println(i +" is less than zero");
}
else
{
System.out.println(" it is zero");
}
}
}

26
• Java if-else-if ladder is used to decide among multiple options. The if
statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if
is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
if (condition1) {
// codes
}
else if(condition2) {
// codes
}
else if (condition3) {
// codes
}
.
.
else {
// codes
27
}

import java.util.*;
class Results
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

int res=System.out.println("Enter marks :");


if(res>=70)
{
System.out.println("passed with distinction");
}

28
else if(res>=60)
{
System.out.println(" passed with first class");
}
else if(res>=50)
{
System.out.println(" passed with second class");
}
else if(res>=40)
{
System.out.println(" passed with third class");
}
else
{
System.out.println(" sorry Fail");
}
}
}

29
Java 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. Since Java 7, you can use strings in
the switch statement.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

30
Example 1
class Switch
{
public static void main(String args[])
{
int branch=4;
switch(branch)
{
case 1:
System.out.println("Civil Engineering");
break;
case 2:
System.out.println("Electrical Engineering");
break;
case 3:
31
System.out.println("Mechanical Engineering");
break;
case 4:
System.out.println("Electronics communication Engineering");
break;
case 5:
System.out.println("Computer Science Engineering");
break;
default:
System.out.println("invalid branch");
}
}
}

Example 2
class Switch1{

32
public static void main(String args[]){
int day=8;
switch(day){
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("invalid day");

33
}
}
}

Loops in Java
• In programming languages, loops are used to execute a set of
instructions/functions repeatedly when some conditions become true.
There are three types of loops in Java.
• for loop
• while loop
• do-while loop
Java While Loop
• The Java while loop is used to iterate a part of the program several
times. If the number of iteration is not fixed, it is recommended to use
while loop.
• Syntax:
while(condition){

34
//code to be executed
}
While Loop flow chart

//write a program to print 1 to 10 nos


class WhileLoop
{
public static void main(String args[])
{
int n=1;
while(n<=10)
{
System.out.print(n +" ");
n++;//n=n+1
}
}

35
}

// Write a program for finding the factorial of given no


class Fact
{
public static void main(String args[])
{
int n=5;
int fact=1;
while(n>0)
{
fact=fact*n;
n--;//n=n+1
}
System.out.print(" factorial : "+ fact);
}
}

36
Java do-while Loop
• The Java do-while loop is used to iterate a part of the program several
times. If the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use do-while loop.
• The Java do-while loop is executed at least once because condition is
checked after loop body.
• Syntax:
do{
//code to be executed
}while(condition);
do-while Loop flow chart

37
//print numbers which are divisible by 5 and 15
class Dowhile
{
public static void main(String args[])
{
int a=1;
do{
if(a%5==0 || a%15==0)
System.out.print(a+ " ");
a++;//a=a+1
}while(a<=100);
}
}

38
Java For Loop
• The Java for loop is used to iterate a part of the program several times.
If the number of iteration is fixed, it is recommended to use for loop.
Flow chart for loop

39
syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been
executed.

//write a program to print 1 to 50 even numbers

class Forloop

public static void main(String args[])

int n=50;

for(int i=2;i<=n;i+=2)

System.out.print(i+" ");

}}

40
Break statement in java
• The break statement in Java programming language has the following
two usages −
• When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
• It can be used to terminate a case in the switch statement Syntax
• The syntax of a break is a single statement inside any loop −
break;
flow chart of break

41
class BBreak
{
public static void main(String args[])
{
for(int i=1;i<10000;i++)
{
if(i==10)
{
break;
}
System.out.print(i+" ");
}
}
}

42
Java Continue Statement
• The continue statement is used in loop control structure when you need
to jump to the next iteration of the loop immediately. It can be used
with for loop or while loop.
• The Java continue statement is used to continue the loop. It continues
the current flow of the program and skips the remaining code at the
specified condition. In case of an inner loop, it continues the inner loop
only.
• We can use Java continue statement in all types of loops such as for
loop, while loop and do-while loop.
• Syntax:
jump-statement;
continue;
class Continue
{
public static void main(String args[])
{

43
for(int i=1;i<=10;i++)
{
if(i%2==0)
{
continue;
}
System.out.print(i +" ");
}
}
}

44

You might also like