Module 2.Docx
Module 2.Docx
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.
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
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.
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
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.
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:
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) {
}`
Output
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 ,
● == , 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.
● &&, 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
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 ,
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
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.
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;
}`
Output
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 ,
● << (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 ,
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
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
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
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.
Output
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.
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.
> (signed right shift) preserves the sign bit, while >>> (unsigned right shift) always fills the
leftmost bits with 0.
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.
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,
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)
}`
Output
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){
// condition is true
}else{
// condition is false
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
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) {
if (condition2)
{
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) {
}`
Output
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) {
} else if (condition2) {
// code to be executed if condition2 is true
} else {
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
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:
break;
case value2:
break;
// more cases…
default:
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.
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.
// 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