Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

UNIT-II

Java Operators
Operators are symbols that perform operations on variables and values. For example, + is an operator
used for addition, while * is also an operator used for multiplication.

Operators in Java can be classified into 5 types:

Arithmetic Operators

Assignment Operators

Relational Operators

Logical Operators

Unary Operators

Bitwise Operators

Java Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For example,

C = a+b;

Here, the + operator is used to add two variables a and b. Similarly, there are various other arithmetic
operators in Java.

Operator Operation

+ Addition

- Subtraction

Multiplication
*

Division
/

Modulo Operation (Remainder after division)


%
Assignment Operators

Assignment operators are used in Java to assign values to variables. For example,

Int name;

Name = “kafil”;

Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That
is, kafil is assigned to the variable name.

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;

Write a program to demonstrate assignment operator in java.

class test{
public static void main(String args[]){
int a=20;
a+=a; //assigning the value a+a into a variable
System.out.println("assignment += operator to add a=a+a = "+a);
}
}
Relational Operators

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

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

Write a program to demonstrate Relation operator.

class test{
public static void main(String args[]){
int a=20,b=30;
if(a==b)
System.out.println("Both are equal"+a+" "+b);
else
System.out.println("Both are not equal "+a+" "+b);
}
}

2nd example:

class test{
public static void main(String args[]){
int a=20,b=70;
double d=10.76;
char c='a';
char m='A';
boolean t; //error
boolean f; //error
if(a>b)
System.out.println("A is greater number");
else
System.out.println("B is greater number");
}
}
Note: Relation operators can be used for all primitive data types accept Boolean and object type.

Logical Operators

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 && expression2 true only if both 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

Write a program to demonstrate Logical operator.


Greatest number :
class test{
public static void main(String args[]){
int a=10,b=20,c=14;
if(a>b && a>c)
System.out.println("A is greatest number "+a);
else if(b>a && b>c)
System.out.println("B is greatest number "+b);
else
System.out.println("C is greatest number "+c);
}
}
Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a number. They can be
used with any type (char, short, int, etc.). They are used when performing update and query operations
of the Binary indexed trees.
Now let’s look at each one of the bitwise operators in Java:

Operators Symbol Uses

Bitwise AND & op1 & op2

Bitwise exclusive OR ^ op1 ^ op2

Bitwise inclusive OR | op1 | op2


Write a program to demonstrate Bitwise operator.
Greatest number :
class test{
public static void main(String args[]){
int a=10,b=20,c=14;
if(a>b & a>c)
System.out.println("A is greatest number "+a);
else if(b>a & b>c)
System.out.println("B is greatest number "+b);
else
System.out.println("C is greatest number "+c);
}
}

Control Statements in Java


Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java

provides statements that can be used to control the flow of Java code. Such statements are called
control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of
program.

Flow of control

Java control flow describe that on which order execution of the program will be done.

Types of Control Statements

Java provides three types of control flow statements.

1. Decision Making statements

1.if statements

2. switch statement

2. Loop statements/Iterative statements

1. do while loop

2. while loop

3. for loop

4. for-each loop

3. Transfer statements/Jump statements

1. break statement
2. continue statement

3. return statement

Decision making statements

As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow depending
upon the result of the condition provided. There are two types of decision-making statements in Java,
i.e., If statement and switch statement .

1. Simple If statements
2. The Java if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a certain
condition is true then a block of statement is executed otherwise not.

if(condition)
{
// Statements to execute if
// condition is true
}

// Java program to illustrate If statement

class IfDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
System.out.println("10 is less than 15");

System.out.println("Outside if-block");
// both statements will be printed
}
}

Java if-else statement

The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with the if statement to execute a block of code
when the condition is false

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
class IfElseDemo {
public static void main(String args[])
{
int i = 20;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");

System.out.println("Outside if-else block");


}
}
Java if-else-if ladder

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 (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
// Java program to illustrate if-else-if ladder

import java.io.*;

class GFG {
public static void main(String[] args)
{
// initializing expression
int i = 20;

// condition 1
if (i == 10)
System.out.println("i is 10\n");

// condition 2
else if (i == 15)
System.out.println("i is 15\n");

// condition 3
else if (i == 20)
System.out.println("i is 20\n");

else
System.out.println("i is not present\n");

System.out.println("Outside if-else-if");
}
}
Switch Statement
The switch statement is a multi-way branch statement. In simple words, the Java switch
statement executes one statement from multiple conditions. It is like an if-else-if ladder
statement. It provides an easy way to dispatch execution to different parts of code based on the
value of the expression. Basically, the expression can be a byte, short, char, and int primitive
data types. It basically tests the equality of variables against multiple values.

// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 :
// Statements
break; // break is optional

case value2 :
// Statements
break; // break is optional

// We can have any number of case statements


// below is default statement, used when none of the cases is true.
// No break is needed in the default case.
default :
// Statements
}

While control statement


The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean
condition is true. As soon as the Boolean condition becomes false, the loop automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is
recommended to use the while loop.

Syntax:

while (condition){
//code to be executed
Increment / decrement statement
}
Example:
class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}

Output:

1
2
3
4
5
6
7
8
9
10

Do while loop control statement


The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition
is true. If the number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while
check the condition at the end of loop body. The Java do-while loop is executed at least once because
condition is checked after loop body.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
Example:
class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}

Output:

1
2
3
4
5
6
7
8
9
10

For loop control statement


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.
There are three types of for loops in Java.

Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}

//Java Program to demonstrate the example of for loop


//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Nested for Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *

Java for-each Loop


The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop
because we don't need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one by one in the defined
variable.

Syntax:

for(data_type variable : array_name){


//code to be executed
}
Java For-each loop example which prints the
elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Labeled For Loop

We can have a name of each Java for loop. To do so, we use label before the for loop. It
is useful while using the nested for loop as we can break/continue specific for loop.

Syntax:

labelname:
for(initialization; condition; increment/decrement){
//code to be executed
}
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Continue statement
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.
//Java Program to demonstrate the use of continue statement
//inside the for loop.
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it will skip the rest statement
}
System.out.println(i);
}
}
}

Output:

1
2
3
4
6
7
8
9
10

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements.
We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in Java which grows automatically.
Single Dimensional Array in Java
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Declaration creation and initialization at the same time
Int[] x = new int[]{10,20,30,40,50};
Example :
Write a program to display an array
class test{
public static void main(String args[]){
int []x = new int[]{10,20,30,40,50};
for(int i=0;i<=4;i++)
System.out.println(x[i]);
}
}

One dimension array input type in java example:


Write a program to take array elements input from user and display it.

import java.util.Scanner;
class test{
public static void main(String args[]){
//int[] x;
int []x = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("enter the elements");
for(int i=0;i<=4;i++)
x[i] = sc.nextInt();
System.out.println("the elements of array ");
for(int i=0;i<=4;i++)
System.out.println(x[i]);
}
}

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
example:
int[][] x;

Creating two dimensional array

int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

1. x[0][0]=1;
2. x[0][1]=2;
3. x[0][2]=3;
4. x[1][0]=4;
5. x[1][1]=5;
6. x[1][2]=6;
7. x[2][0]=7;
8. x[2][1]=8;
9. x[2][2]=9;

Write a program to display 2d array in java using for each loop.

class test{
public static void main(String args[]){
int [][]x = new int[][]{{10,20,30},{40,50,60},{70,80,90}};
System.out.println("the elements of array ");
for(int[] x1:x){
for(int x2:x1 ){
System.out.print(" "+x2);
}
System.out.println(" ");
}
}
}

Write a program to insert 2d array and display it as matrix form

import java.util.Scanner;
class test{
public static void main(String args[]){
//int[] x;
int [][]x = new int[3][3];
Scanner sc = new Scanner(System.in);
System.out.println("enter the elements");
for(int i=0;i<=2;i++)
for(int j=0;j<=2;j++)
x[i][j] = sc.nextInt();
System.out.println("the elements of array ");
for(int[] x1:x){
for(int x2:x1 ){
System.out.print(" "+x2);
}
System.out.println(" ");
}
}
}
Output

123

456
789

You might also like