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

Module 2.Docx

The document provides an overview of Java operators, categorizing them into arithmetic, unary, assignment, relational, logical, ternary, bitwise, shift, and instanceof operators. Each category is explained with examples demonstrating their functionality and usage in Java programming. Additionally, it discusses operator precedence and associativity, along with interesting questions related to operator behavior in hybrid equations.

Uploaded by

sukunansr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Module 2.Docx

The document provides an overview of Java operators, categorizing them into arithmetic, unary, assignment, relational, logical, ternary, bitwise, shift, and instanceof operators. Each category is explained with examples demonstrating their functionality and usage in Java programming. Additionally, it discusses operator precedence and associativity, along with interesting questions related to operator behavior in hybrid equations.

Uploaded by

sukunansr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Java operators are special symbols that perform operations on variables or values.

They can
be classified into several categories based on their functionality. These operators play a
crucial role in performing arithmetic, logical, relational, and bitwise operations etc.

Example: Here, we are using + and – operators.

Java` // Java program to show the use of + and - operators public class Geeks { public static
void main(String[] args) {

// Declare and initialize variables int num1 = 500; int num2 = 100; // Using the + (addition)
operator int sum = num1 + num2; System.out.println("The Sum is: "+sum); // Using the -
(subtraction) operator int diff = num1 - num2; System.out.println("The Difference is: "+diff);
}

}`

Output

The Sum is: 600 The Difference is: 400

Types of Operators in Java


1.​ Arithmetic Operators
2.​ Unary Operators
3.​ Assignment Operator
4.​ Relational Operators
5.​ Logical Operators
6.​ Ternary Operator
7.​ Bitwise Operators
8.​ Shift Operators
9.​ instance of operator

Let’s see all these operators one by one with their proper examples.

1. Arithmetic Operators

Arithmetic Operators are used to perform simple arithmetic operations on primitive and
non-primitive data types.

●​ \* : Multiplication
●​ / : Division
●​ % : Modulo
●​ + : Addition
●​ – : Subtraction

Example:

Java` // Java Program to show the use of // Arithmetic Operators import java.io.*; class Geeks
{ public static void main (String[] args) {
// Arithmetic operators on integers int a = 10; int b = 3; // Arithmetic operators on Strings
String n1 = "15"; String n2 = "25"; // Convert Strings to integers int a1 = Integer.parseInt(n1);
int b1 = Integer.parseInt(n2); 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)); System.out.println("a1 + b1 = " + (a1 + b1)); }

}`

Output

a + b = 13 a - b = 7 a * b = 30 a / b = 3 a % b = 1 a1 + b1 = 40

2. Unary Operators

Unary Operators need only one operand. They are used to increment, decrement, or negate a
value.

●​ - , Negates the value.


●​ + , Indicates a positive value (automatically converts byte, char, or short to int).
●​ ++ , Increments by 1.
o​ Post-Increment: Uses value first, then increments.
o​ Pre-Increment: Increments first, then uses value.
●​ -- , Decrements by 1.
o​ Post-Decrement: Uses value first, then decrements.
o​ Pre-Decrement: Decrements first, then uses value.
●​ ! , Inverts a boolean value.

Example:

Java// Java Program to show the use of // Unary Operators import java.io.*; // Driver Class
class Geeks { // main function public static void main(String[] args) { // Interger declared int
a = 10; int b = 10; // Using unary operators System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a)); System.out.println("Postdecrement : " + (b--));
System.out.println("Predecrement : " + (--b)); } }

Output

Postincrement : 10 Preincrement : 12 Postdecrement : 10 Predecrement : 8

3. Assignment Operator

‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left
associativity, 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;
In many cases, the assignment operator can be combined with others to create shorthand
compound statements. For example, a += 5 replaces a = a + 5. Common compound operators
include:

●​ += , Add and assign.


●​ -= , Subtract and assign.
●​ *= , Multiply and assign.
●​ /= , Divide and assign.
●​ %= , Modulo and assign.

Example:

Java` // Java Program to show the use of // Assignment Operators import java.io.*; // Driver
Class class Geeks { // Main Function public static void main(String[] args) {

// Assignment operators int f = 7; System.out.println("f += 3: " + (f += 3));


System.out.println("f -= 2: " + (f -= 2)); System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3)); System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010)); System.out.println("f |= 0b1100: " + (f
|= 0b1100)); System.out.println("f ^= 0b1010: " + (f ^= 0b1010)); System.out.println("f <<=
2: " + (f <<= 2)); System.out.println("f >>= 1: " + (f >>= 1)); System.out.println("f >>>= 1: "
+ (f >>>= 1)); }

}`

Output

f += 3: 10 f -= 2: 8 f *= 4: 32 f /= 3: 10 f %= 2: 0 f &= 0b1010: 0 f |= 0b1100: 12 f ^=


0b1010: 6 f <<= 2: 24 f >>= 1: 12 f >>>= 1: 6

4. Relational Operators

Relational 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

Relational operators compare values and return boolean results:

●​ == , Equal to.
●​ != , Not equal to.
●​ < , Less than.
●​ <= , Less than or equal to.
●​ > , Greater than.
●​ >= , Greater than or equal to.

Example:
Java// Java Program to show the use of // Relational Operators import java.io.*; // Driver
Class class Geeks { // main function public static void main(String[] args) { // Comparison
operators int a = 10; int b = 3; int c = 5; 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 == c: " + (a == c));
System.out.println("a != c: " + (a != c)); } }

Output

a > b: true a < b: false a >= b: true a <= b: false a == c: false a != c: true

5. Logical Operators

Logical Operators are used to perform “logical AND” and “logical OR” operations, similar to
AND gate and OR gate in digital electronics. They have a short-circuiting effect, meaning the
second condition is not evaluated if the first is false.

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

Example:

Java` // Java Program to show the use of // Logical operators import java.io.*; class Geeks {

// Main Function public static void main (String[] args) { // Logical operators boolean x =
true; boolean y = false; System.out.println("x && y: " + (x && y)); System.out.println("x || y:
" + (x || y)); System.out.println("!x: " + (!x)); }

}`

Output

x && y: false x || y: true !x: false

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

The above statement means that if the condition evaluates to true, then execute the statements
after the ‘?’ else execute the statements after the ‘:’.

Example:
Java` // Java program to illustrate // max of three numbers using // ternary operator. public
class Geeks {

public static void main(String[] args) { int a = 20, b = 10, c = 30, result; // result holds max of
three // numbers result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c); System.out.println("Max of
three numbers = "+ result); }

}`

Output

Max of three numbers = 30

7. Bitwise Operators

Bitwise Operators are used to perform the manipulation of individual bits of a number and
with any of the integer types. They are used when performing update and query operations of
the Binary indexed trees.

●​ & (Bitwise AND) – returns bit-by-bit AND of input values.


●​ | (Bitwise OR) – returns bit-by-bit OR of input values.
●​ ^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
●​ ~ (Bitwise Complement) – inverts all bits (one’s complement).

Example:

Java` // Java Program to show the use of // bitwise operators import java.io.*; class Geeks {
public static void main(String[] args) { // Bitwise operators int d = 0b1010; int e = 0b1100;

System.out.println("d & e : " + (d & e)); System.out.println("d | e : " + (d | e));


System.out.println("d ^ e : " + (d ^ e)); System.out.println("~d : " + (~d));
System.out.println("d << 2 : " + (d << 2)); System.out.println("e >> 1 : " + (e >> 1));
System.out.println("e >>> 1 : " + (e >>> 1)); }

}`

Output

d & e : 8 d | e : 14 d ^ e : 6 ~d : -11 d << 2 : 40 e >> 1 : 6 e >>> 1 : 6

8. Shift Operators

Shift 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. The general format ,

number shift_op number_of_places_to_shift;

●​ << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of two).
●​ >> ( Signed right shift) – Shifts bits right, filling 0s (divides by a power of two), with
the leftmost bit depending on the sign.
●​ >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the leftmost bit always
0.

Example:

Java` // Java Program to show the use of // shift operators import java.io.*; class Geeks {
public static void main(String[] args) { int a = 10;

// Using left shift System.out.println("a<<1 : " + (a << 1)); // Using right shift
System.out.println("a>>1 : " + (a >> 1)); }

}`

Output

a<<1 : 20 a>>1 : 5

9. instanceof operator

The instance of 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. The general format ,

object instance of class/subclass/interface

Java// Java program to show the use of // Instance of operator public class Geeks { public
static void main(String[] args) { Person obj1 = new Person(); Person obj2 = new Boy(); // As
obj is of type person, it is not an // instance of Boy or interface 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)); // Since obj2 is of type boy, // whose parent class is person // and it
implements the interface Myinterface // it is instance of all of these classes
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)); } } //
Classes and Interfaces used // are declared here class Person { } class Boy extends Person
implements MyInterface { } interface MyInterface { }

Output

obj1 instanceof Person: true obj1 instanceof Boy: false obj1 instanceof MyInterface: false
obj2 instanceof Person: true obj2 instanceof Boy: true obj2 instanceof MyInterface: true

Precedence and Associativity of Java Operators


Precedence and associative rules are used when dealing with hybrid equations involving more
than one type of operator. In such cases, these rules determine which part of the equation to
consider first, as there can be many different valuations for the same equation. The below
table depicts the precedence of operators in decreasing order as magnitude, with the top
representing the highest precedence and the bottom showing the lowest precedence.

Interesting Questions About Java Operators


1. Precedence and Associativity

There is often confusion when it comes to hybrid equations which are equations having
multiple operators. The problem is which part to solve first. There is a golden rule to follow
in these situations. If the operators have different precedence, solve the higher precedence
first. If they have the same precedence, solve according to associativity, that is, either from
right to left or from left to right. The explanation of the below program is well written in
comments within the program itself.

Javapublic class GFG { public static void main(String[] args) { int a = 20, b = 10, c = 0; int d
= 20, e = 40, f = 30; // precedence rules for arithmetic operators. // (* = / = %) > (+ = -) //
prints a+(b/d) System.out.println("a+b/d = " + (a + b / d)); // if same precedence then
associative // rules are followed. // e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f)
System.out.println("a+b*d-e/f = " + (a + b * d - e / f)); } }

Output

a+b/d = 20 a+b*d-e/f = 219

2. Be a Compiler

The compiler in our systems uses a lex tool to match the greatest match when generating
tokens. This creates a bit of a problem if overlooked. For example, consider the statement
a=b+++c; too many of the readers might seem to create a compiler error. But this statement is
absolutely correct as the token created by lex is a, =, b, ++, +, c. Therefore, this statement has
a similar effect of first assigning b+c to a and then incrementing b. Similarly, a=b+++++c;
would generate an error as the tokens generated are a, =, b, ++, ++, +, c. which is actually an
error as there is no operand after the second unary operand.

Java` public class GFG { public static void main(String[] args) { int a = 20, b = 10, c = 0; //
a=b+++c is compiled as // b++ +c // a=b+c then b=b+1 a = b++ + c;

System.out.println("Value of a(b+c), " + " b(b+1), c = " + a + ", " + b + ", " + c); //
a=b+++++c is compiled as // b++ ++ +c // which gives error. // a=b+++++c; //
System.out.println(b+++++c); }

}`

Output

Value of a(b+c), b(b+1), c = 10, 11, 0


3. Using + over ()

When using the + operator inside system.out.println() make sure to do addition using
parenthesis. If we write something before doing addition, then string addition takes place, that
is, associativity of addition is left to right, and hence integers are added to a string first
producing a string, and string objects concatenate when using +. Therefore it can create
unwanted results.

Javapublic class GFG { public static void main(String[] args) { int x = 5, y = 8; //


concatenates x and y as // first x is added to "concatenation (x+y) = " // producing
"concatenation (x+y) = 5" // and then 8 is further concatenated.
System.out.println("Concatenation (x+y) = " + x + y); // addition of x and y
System.out.println("Addition (x+y) = " + (x + y)); } }Try it on GfG Practice \ \

Output

Concatenation (x+y)= 58 Addition (x+y) = 13

Advantages of Operators
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
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.

FAQs – Operators in Java


What is operators in Java with example?

Operators are the special symbols that are used for performing certain operations. For
example, ‘+’ is used for addition where 5+4 will return the value 9.
How do shift operators work in Java?

Shift operators (<<, >>, >>>) move the bits of a number to the left or right, effectively
multiplying or dividing the number by powers of two.

What is the difference between signed and unsigned right shift?

> (signed right shift) preserves the sign bit, while >>> (unsigned right shift) always fills the
leftmost bits with 0.

Can operators be overloaded in Java?

No, Java does not support operator overloading.

Decision-Making Statements
Decision-making statements in Java execute a block of code based on a condition.
Decision-making in programming is similar to decision-making in real life. In programming,
we also face situations where we want a certain block of code to be executed when some
condition is fulfilled.

A programming language uses control statements to control the flow of execution of a


program based on certain conditions. These are used to cause the flow of execution to
advance and branch based on changes to the state of a program.

Types of Decision-Making Statements


●​ if
●​ if-else
●​ nested-if
●​ if-else-if
●​ switch-case
●​ jump – break, continue, return

1. Java if Statement

The 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 statements is executed otherwise not.

Syntax:

if(condition) {

// Statements to execute if

// condition is true
}

Here, the condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements under it. If we don’t
use curly braces( {} ), only the next line after the if is considered as part of the if block For
example,

if (condition) // Assume condition is true

statement1; // Belongs to the if block

statement2; // Does NOT belong to the if block

Here’s what happens:

●​ If the condition is True statement1 executes.


●​ statement2 runs no matter what because it’s not a part of the if block

if Statement Execution Flow

The below diagram demonstrates the flow chart of an “if Statement execution flow” in
programming.

Example: The below Java program demonstrates without curly braces, only the first line
after the if statement is part of the if block and the rest code will be execute independently.

Java` // Java program to illustrate // if statement without curly block import java.util.*; class
Geeks { public static void main(String args[]) { int i = 10; if (i < 15)

// part of if block(immediate one statement // after if condition) System.out.println("Inside If


block"); // always executes as it is outside of if block System.out.println("10 is less than 15");
// This statement will be executed // as if considers one statement by default again // below
statement is outside of if block System.out.println("I am Not in if"); }

}`

Output

Inside If block 10 is less than 15 I am Not in if

2. 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.
Syntax:

if(condition){

// Executes this block if

// condition is true

}else{

// Executes this block if

// condition is false

if-else Statement Execution flow

The below diagram demonstrates the flow chart of an “if-else Statement execution flow” in
programming

Example: The below Java program demonstrates the use of if-else statement to execute
different blocks of code based on the condition.

Java// Java program to demonstrate // the working of if-else statement import java.util.*; class
Geeks { public static void main(String args[]) { int i = 10; if (i < 15) System.out.println("i is
smaller than 15"); else System.out.println("i is greater than 15"); } }

Output

i is smaller than 15

3. Java nested-if Statement

A nested if is an if statement that is the target of another if or else. Nested if statements mean
an if statement inside an if statement. Yes, java allows us to nest if statements within if
statements. i.e, we can place an if statement inside another if statement.

Syntax:

if (condition1) {

// Executes when condition1 is true

if (condition2)
{

// Executes when condition2 is true

nested-if Statement Execution Flow

The below diagram demonstrates the flow chart of an “nested-if Statement execution flow” in
programming

Example: The below Java program demonstrates the use of nested if statements to check
multiple conditions.

Java` // Java program to demonstrate the // working of nested-if statement import java.util.*;
class Geeks { public static void main(String args[]) { int i = 10; if (i == 10 || i < 15) {

// First if statement if (i < 15) System.out.println("i is smaller than 15"); // Nested - if


statement // Will only be executed if statement above // it is true if (i < 12)
System.out.println( "i is smaller than 12 too"); } else { System.out.println("i is greater than
15"); } }

}`

Output

i is smaller than 15 i is smaller than 12 too

4. Java if-else-if ladder

Here, a user can 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. There can be as many as ‘else if’ blocks
associated with one ‘if’ block but only one ‘else’ block is allowed with one ‘if’ block.

Syntax:

if (condition1) {

// code to be executed if condition1 is true

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

} else {

// code to be executed if all conditions are false

if-else-if ladder Execution Flow

The below diagram demonstrates the flow chart of an “if-else-if ladder execution flow” in
programming

Example:

Java// Java program to demonstrate the // working of if-else-if ladder import java.util.*; class
Geeks { public static void main(String args[]) { int i = 20; if (i == 10) System.out.println("i is
10"); else if (i == 15) System.out.println("i is 15"); else if (i == 20) System.out.println("i is
20"); else System.out.println("i is not present"); } }

Output

i is 20

5. Java Switch Case

The switch statement is a multiway branch statement. It provides an easy way to dispatch
execution to different parts of code based on the value of the expression.

Syntax:

switch (expression) {

case value1:

// code to be executed if expression == value1

break;

case value2:

// code to be executed if expression == value2

break;

// more cases…
default:

// code to be executed if no cases match

switch Statements Execution Flow

The below diagram demonstrates the flow chart of a “switch Statements execution flow” in
programming.

Example: The below Java program demonstrates the use of if-else-if ladder to check multiple
conditions.

Java// Java program to demonstrates the // working of switch statements import java.io.*;
class Geeks { public static void main(String[] args) { int num = 20; switch (num) { case 5:
System.out.println("It is 5"); break; case 10: System.out.println("It is 10"); break; case 15:
System.out.println("It is 15"); break; case 20: System.out.println("It is 20"); break; default:
System.out.println("Not present"); } } }

Output

It is 20

●​ The expression can be of type byte, short, int char, or an enumeration. Beginning with
JDK7, the expression can also be of type String.
●​ Duplicate case values are not allowed.
●​ The default statement is optional.
●​ The break statement is used inside the switch to terminate a statement sequence.
●​ The break statements are necessary without the break keyword, statements in switch
blocks fall through.
●​ If the break keyword is omitted, execution will continue to the next case.

6. jump Statements

Java supports three jump statements: break, continue and return. These three statements
transfer control to another part of the program.

●​ Break: In Java, a break is majorly used for:


o​ Terminate a sequence in a switch statement (discussed above).
o​ To exit a loop.
o​ Used as a “civilized” form of goto.
●​ Continue: Sometimes it is useful to force an early iteration of a loop. That is, you
might want to continue running the loop but stop processing the remainder of the code
in its body for this particular iteration. This is, in effect, a goto just past the body of
the loop, to the loop’s end. The continue statement performs such an action.
jump Statements Execution Flow

The below diagram demonstrates the flow chart of a “jump Statements execution flow” in
programming.

Example: The below Java Program demonstrates how the continue statement skip the current
iteration when a condition is true.

Java` // Java program to demonstrates the use of // continue in an if statement import


java.util.*; class Geeks { public static void main(String args[]) { for (int i = 0; i < 10; i++) {

// If the number is even // skip and continue if (i % 2 == 0) continue; // If number is odd, print
it System.out.print(i + " "); } }

}`

Output

13579

Return Statement

The return statement is used to explicitly return from a method. That is, it causes program
control to transfer back to the caller of the method.

Example: The below Java program demonstrates how the return statements stop a method
and skips the rest of the code.

Java// Java program to demonstrate the use of return import java.util.*; public class Geeks {
public static void main(String args[]) { boolean t = true; System.out.println("Before the
return."); if (t) return; // Compiler will bypass every statement // after return
System.out.println("This won't execute."); } }Try it on GfG Practice \ \

Output

Before the return.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy