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

Unit2 Java

The document discusses the different types of operators in Java including arithmetic, unary, assignment, relational, logical, ternary, bitwise, and shift operators. It provides examples of how to use each type of operator in Java code along with the expected output.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit2 Java

The document discusses the different types of operators in Java including arithmetic, unary, assignment, relational, logical, ternary, bitwise, and shift operators. It provides examples of how to use each type of operator in Java code along with the expected output.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

1

JAVA PROGRAMMING (C - 401)

What are the Java Operators?


Operators in Java are the symbols used for performing specific operations in Java. Operators make tasks like
addition, multiplication, etc which look easy although the implementation of these tasks is quite complex.

Types of Operators in Java

There are multiple types of operators in Java all are mentioned below:

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators

1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
Output
 – : Subtraction a + b = 13

class test { a - b = 7
// Main Function a * b = 30
public static void main (String[] args) {
a / b = 3
// Arithmetic operators a % b = 1
int a = 10;
int b = 3;

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));
System.out.println("a % b = " + (a % b));

}
}

2. Unary Operators
Unary operators need only one operand. They are used to increment and decrement value.

++: Increment operator, used for incrementing the value by 1. There are two varieties of increment
operators.
 Post-Increment: Value is first used for computing the result and then incremented.
 Pre-Increment: Value is incremented first, and then the result is computed.

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


2
JAVA PROGRAMMING (C - 401)

– –: Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.
 Post-decrement: Value is first used for computing the result and then decremented.
 Pre-Decrement: The value is decremented first, and then the result is computed.

// Java Program to implement

// Uniary Operators

import java.io.*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)

// Integer declared

int a = 10;

int b = 10;
Output
Postincrement : 10
Preincrement : 12
// Using uniary operators
Postdecrement : 10
System.out.println("Postincrement : " + (a++)); Predecrement : 8
System.out.println("Preincrement : " + (++a));

System.out.println("Postdecrement : " + (b--));

System.out.println("Predecrement : " + (--b));

3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associatively, i.e. value
given on the right-hand side of the operator is assigned to the variable on the left, and therefore right-hand
side value must be declared before using it or should be a constant.
The general format of the assignment operator is:

Variable = value;

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


3
JAVA PROGRAMMING (C - 401)

In many cases, the assignment operator can be combined with other operators to build a shorter
version of the statement called a Compound Statement. For example, instead of a = a+5, we can
write a += 5.
 +=, for adding the left operand with the right operand and then assigning it to the variable on the
left.
 -=, for subtracting the right operand from the left operand and then assigning it to the variable on
the left.
 *=, for multiplying the left operand with the right operand and then assigning it to the variable on
the left.
 /=, for dividing the left operand by the right operand and then assigning it to the variable on the
left.
 %=, for assigning the modulo of the left operand by the right operand and then assigning it to the
variable on the left.

import java.io.*;

// Driver Class Output


class test {
// Main Function
f += 3: 10
public static void main(String[] args) f -= 2: 8
{
f *= 4: 32
// Assignment operators
int f = 7; f /= 3: 10
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2)); f %= 2: 0
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3)); f &= 0b1010: 0
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010)); f |= 0b1100: 12
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
f ^= 0b1010: 6
System.out.println("f <<= 2: " + (f <<= 2));
f <<= 2: 24
System.out.println("f >>= 1: " + (f >>= 1));
f >>= 1: 12
}
}

4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than. They return
boolean results after the comparison and are extensively used in looping statements as well as
conditional if-else statements. The general format is,

variable relation_operator value

Some of the relational operator’s are-


 ==, Equal to returns true if the left-hand side is equal to the right-hand side.
 !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
 <, less than: returns true if the left-hand side is less than the right-hand side.
 <=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand
side.
 >, Greater than: returns true if the left-hand side is greater than the right-hand side.
 >=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-
hand side.
UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)
4
JAVA PROGRAMMING (C - 401)

import java.io.*;

// Driver Class
Output
class test { a > b: true
// main function
public static void main(String[] args) a < b: false
{
// Comparison operators a >= b: true
int a = 10;
int b = 3;
a <= b: false
int c = 5; a == c: false
System.out.println("a > b: " + (a > b)); a != c: true
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 == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}

5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function similar
to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is
not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for
several conditions for making a decision. Java also has “Logical NOT”, which returns true when the
condition is false and vice-versa,
Conditional operators are:
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-versa

import java.io.*;

// Driver Class
class test {
Output
// Main Function x && y: false
public static void main (String[] args) {
// Logical operators x || y: true
boolean x = true;
boolean y = false; !x: false

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


System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}

6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the
name Ternary.

The general format is:


condition ? if true : if false

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


5
JAVA PROGRAMMING (C - 401)

class operators {
public static void main(String[] args)
{
int a = 20, b = 10, result;

// result holds max of two


// numbers
Result = (a > b) ? a : b ;
System.out.println("Max of two numbers = "+ result);
}
}
Output
Max of two numbers = 20
7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a number. They can be used with
any of the integer types. They are used when performing update and query operations of the Binary indexed
trees.
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns the one’s

import java.io.*;
OUTPUT
// Driver class
class test {
// main function
d & e: 4
public static void main(String[] args)
{ d | e: 5
// Bitwise operators
int d = 4; d ^ e: 1
int e = 5;
System.out.println("d & e: " + (d & e)); ~d: -5
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
}
}

Advantages of Operators in Java


The advantages of using operators in Java are mentioned below:
1. Expressiveness: Operators in Java provide a concise and readable way to perform complex calculations
and logical operations.
2. Time-Saving: Operators in Java save time by reducing the amount of code required to perform certain
tasks.
3. Improved Performance: Using operators can improve performance because they are often implemented
at the hardware level, making them faster than equivalent Java code.

Disadvantages of Operators in Java


The disadvantages of Operators in Java are mentioned below:
1. Operator Precedence: Operators in Java have a defined precedence, which can lead to unexpected results
if not used properly.
2. Type Coercion: Java performs implicit type conversions when using operators, which can lead to
unexpected results or errors if not used properly.
3. Overloading: Java allows for operator overloading, which can lead to confusion and errors if different
classes define the same operator with different behavior.

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


6
JAVA PROGRAMMING (C - 401)

Java If-else Statement

The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in Java.

o if statement
o if-else statement
o if-else-if ladder
o nested if statement

Java if Statement

The Java if statement tests the condition. It executes the if block if condition is true.

Syntax:

If (condition) {
//code to be executed
}
//Java Program to demonstate the use of if statement.
public class IfExample { Output:
public static void main(String[] args) { Age is greater than 18
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}

Java if-else Statement

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
}

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


7
JAVA PROGRAMMING (C - 401)

class IfElseExample {
public static void main(String[] args) {
Output:
//defining a variable
int number=13; odd number
//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");
}
} }

Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

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
}

//Java Program to demonstrate the use of If else-if ladder.


//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


8
JAVA PROGRAMMING (C - 401)

System.out.println("C grade");
}
else if(marks>=70 && marks<80){
Output:
System.out.println("B grade");
} C 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!");
}
}
}

Program to check POSITIVE, NEGATIVE or ZERO:


public class PositiveNegativeExample {
public static void main(String[] args) {
int number=-13;
Output:
if(number>0){
System.out.println("POSITIVE"); NEGATIVE
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
} } }

Java Nested if statement

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
}
}

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


9
JAVA PROGRAMMING (C - 401)

Example:

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
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");
}
}

Output:

You are eligible to donate blood

Example 2:

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//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"); Output:
}
} } You are not eligible to donate blood

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


1
0 JAVA PROGRAMMING (C - 401)

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.

In other words, the switch statement tests the equality of a variable against multiple values.

Syntax:

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;
}

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


1
1 JAVA PROGRAMMING (C - 401)

Example:

SwitchExample.java

public class SwitchExample {


public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
Output:
case 30: System.out.println("30");
break; 20
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
} } }

Program to check Vowel or Consonant:

If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive.

SwitchVowelExample.java

case 'A':
class SwitchVowelExample {
System.out.println("Vowel"); break;
public static void main(String[] args) {
case 'E':
char ch='O';
System.out.println("Vowel"); break;
switch(ch)
case 'I':
{
System.out.println("Vowel"); break;
case 'a':
case 'O':
System.out.println("Vowel"); break;
System.out.println("Vowel"); break;
case 'e':
case 'U':
System.out.println("Vowel"); break;
System.out.println("Vowel"); break;
case 'i':
default:
System.out.println("Vowel"); break;
System.out.println("Consonant");
case 'o':
} } }
System.out.println("Vowel"); break;
case 'u': Output:
System.out.println("Vowel"); break;
Vowel

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


1
2 JAVA PROGRAMMING (C - 401)

Loops in Java

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.

Looping in programming languages is a feature which facilitates the execution of a set of


instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for
executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and
condition checking time.

Java provides three types of Conditional statements this second type is loop statement.
 While loop: A while loop is a control flow statement that allows code to be executed repeatedly based on
a given Boolean condition. The while loop can be thought of as a repeating if statement.
 While loop starts with the checking of Boolean condition. If it evaluated to true, then the loop
body statements are executed otherwise first statement following the loop is executed. For this
reason it is also called Entry control loop.
 Once the condition is evaluated to true, the statements in the loop body are executed. Normally
the statements contain an update value for the variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.

Syntax :
while (boolean condition)
{
loop statements...
}

Import java.io.*;

class test {
public static void main (String[] args) {
int i=0;
while (i<=10)
{
System.out.println(i);
i++;
}
}
}

for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.

for (initialization condition; testing condition;increment/decrement)


{
statement(s)
}

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


1
3 JAVA PROGRAMMING (C - 401)

class test {
public static void main (String[] args) {
for (int i=0;i<=10;i++)
{
System.out.println(i);
}
}
}

 Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
 Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It
is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
 Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.
 Increment/ Decrement: It is used for updating the variable for next iteration.
 Loop termination: When the condition becomes false, the loop terminates marking the end of its life
cycle.

Do while: do while loop is similar to while loop with only difference that it checks for condition after
executing the statements, and therefore is an example of Exit Control Loop.

Syntax:
do
{
statements..
}
while (condition);

Example program
class test {
public static void main (String[] args) {
int i=0;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}

 do while loop starts with the execution of the statement(s). There is no checking of any condition
for the first time.
 After the execution of the statements, and update of the variable value, the condition is checked
for true or false value. If it is evaluated to true, next iteration of loop starts.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.
 It is important to note that the do-while loop will execute its statements at least once before any
condition is checked, and therefore is an example of exit control loop.

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)


1
4 JAVA PROGRAMMING (C - 401)

Write a program to input a number by the user and check number is prime number or not.

Import java.io.Scanner;
class test {
public static void main (String args[]) {
Scanner obj = new Scanner (System.in);
System.out.print(“Enter the number”);
int n = obj.nextInt();
int pr=0;
for (i=2;i<n;i++)
{
if(n%i == 0)
pr++;
}
if(pr==0)
System.out.print(“Number is prime”);
else
System.out.print(“Number is prime”);
}
}

Difference between While & Do while

while do-while

Condition is checked first then statement(s) is Statement(s) is executed atleast once,


executed. thereafter condition is checked.

It might occur statement(s) is executed zero


At least once the statement(s) is executed.
times, If condition is false.

No semicolon at the end of while.


Semicolon at the end of while. while(condition);
while(condition)

If there is a single statement, brackets are not


Brackets are always required.
required.

Variable in condition is initialized before the variable may be initialized before or within the
execution of loop. loop.

while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) { statement(s); } do { statement(s); } while(condition);

UNIT - 2 | This file designed by Er.R.Rathor sir (Assistant Professor)

You might also like