[Go to site: main page, start]

0% found this document useful (0 votes)
3 views19 pages

Java Operators

java operators

Uploaded by

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

Java Operators

java operators

Uploaded by

sujitchhetri56
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Operators

Java operators are symbols used to perform operations on variables and


values. They play a key role in expressions, calculations, and decision-
making in programs. Operators help simplify complex logic into concise
statements.

 They follow a defined precedence and associativity to determine


execution order.

 Some operators work on a single operand (unary), while others require


two or more operands.

1. Arithmetic Operators

Arithmetic Operators are used to perform arithmetic operations on primitive


numeric data types such as int, float, and double.

public class PCM{

public static void main(String[] args) {

int a = 10, b = 3;

// Addition

int sum = a + b;

// Subtraction

int diff = a - b;

// Multiplication

int mul = a * b;

// Division

int div = a / b;

// Modulus

int mod = a % b; // Modulus


[Link]("Sum: " + sum);

[Link]("Difference: " + diff);

[Link]("Multiplication: " + mul);

[Link]("Division: " + div);

[Link]("Modulus: " + mod);

Output

Sum: 13

Difference: 7

Multiplication: 30

Division: 3

Modulus: 1

Explanation:

 Two variables a = 10 and b = 3 are used to perform arithmetic


operations.

 Operators like +, -, *, /, and % are applied to calculate sum, difference,


product, division, and remainder.

 Integer division (a / b) returns only the quotient (3), ignoring decimals.

 The results of each operation are stored in variables and printed.

2. Unary Operators

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

import [Link].*;

// Driver Class

class TestClass{
public static void main(String[] args){

// Integer declared

int a = 10;

int b = 10;

// Using unary operators

[Link]("Postincrement : " + (a++));

[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));

[Link]("Predecrement : " + (--b));

Output

Postincrement : 10

Preincrement : 12

Postdecrement : 10

Predecrement : 8

Explanation:

 Unary operators work on a single operand (a and b).

 Post-increment (a++) returns the value first, then increments it.

 Pre-increment (++a) increments first, then returns the updated value.

 Same behavior applies to decrement operators (--).

3. Assignment Operator
The assignment operator assigns a value from the right-hand side to a
variable on the left. Since it has right-to-left associativity, the right-hand
value must be declared or constant.

public class PCM {

public static void main(String[] args) {

// initial value

int num = 10;

[Link]("Initial: " + num);

// add 5 → num = num + 5

num += 5;

[Link]("After +5: " + num);

// multiply by 2 → num = num * 2

num *= 2;

[Link]("After *2: " + num);

// subtract 5 → num = num - 5

num -= 5;

[Link]("After -5: " + num);

// divide by 2 → num = num / 2

num /= 2;

[Link]("After /2: " + num);

// remainder after dividing by 3 → num = num % 3

num %= 3;
[Link]("After %3: " + num);

Output

Initial: 10

After +5: 15

After *2: 30

After -5: 25

After /2: 12

After %3: 0

Explanation:

 The variable num starts with an initial value of 10 and is updated step
by step.

 Compound operators like +=, *=, -=, /=, %= perform operation and
assignment together.

 Each statement changes the same variable, so the result depends on


the previous step.

 The output shows how the value of num changes after each operation.

Note: Use compound assignments (+=, -=) for cleaner code.

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.

import [Link].*;

class TestClass{
public static void main(String[] args){

// Comparison operators

int a = 10;

int b = 3;

int c = 5;

[Link]("a > b: " + (a > b));

[Link]("a < b: " + (a < b));

[Link]("a >= b: " + (a >= b));

[Link]("a <= b: " + (a <= b));

[Link]("a == c: " + (a == c));

[Link]("a != c: " + (a != c));

Output

a > b: true

a < b: false

a >= b: true

a <= b: false

a == c: false

a != c: true

Explanation:

 Variables a, b, and c are compared using relational operators.

 Operators like >, <, >=, <=, ==, != return boolean values.

 These comparisons help in decision-making (if-else, loops).


 Each expression prints either true or false based on the condition.

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.

import [Link].*;

class TestClass {

// Main Function

public static void main (String[] args) {

// Logical operators

boolean x = true;

boolean y = false;

[Link]("x && y: " + (x && y));

[Link]("x || y: " + (x || y));

[Link]("!x: " + (!x));

Output

x && y: false

x || y: true

!x: false

Explanation:

 Boolean variables x and y are used to perform logical operations.

 && (AND) returns true only if both conditions are true.

 || (OR) returns true if at least one condition is true.


 ! (NOT) reverses the boolean value.

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,

public class TestClass{

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

[Link]("Max of three numbers = "+ result);

Output

Max of three numbers = 30

Explanation:

 The ternary operator is used as a shortcut for if-else conditions.

 It evaluates multiple conditions to find the maximum among three


numbers.

 Syntax: (condition) ? value1 : value2.

 Nested ternary operators are used here for compact decision-making.

7. Bitwise Operators

These operators perform operations at the bit level.


 Bitwise Operators manipulate individual bits using AND, OR, XOR, and
NOT.

 Shift Operators move bits to the left or right, effectively multiplying or


dividing by powers of two.

import [Link].*;

class TestClass

public static void main(String[] args)

// Bitwise operators

int d = 0b1010;

int e = 0b1100;

[Link]("d & e : " + (d & e));

[Link]("d | e : " + (d | e));

[Link]("d ^ e : " + (d ^ e));

[Link]("~d : " + (~d));

[Link]("d << 2 : " + (d << 2));

[Link]("e >> 1 : " + (e >> 1));

[Link]("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

Explanation:

 Binary values d and e are used to perform bit-level operations.

 Operators like &, |, ^, ~ manipulate individual bits.

 Shift operators (<<, >>, >>>) move bits left or right.

 These operations are useful in low-level programming and


optimizations.

8. instanceof Operator

The instanceof 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,

public class PCM {

public static void main(String[] args) {

String str = "Hello";

[Link](str instanceof String);

Object obj = 10;

[Link](obj instanceof Integer);

[Link](obj instanceof String);

Output

true

true

false
Explanation:

 The instanceof operator checks the type of an object at runtime.

 It returns true if the object belongs to a specific class or type.

 str instanceof String confirms the type of the string object.

 It helps ensure type safety and avoid runtime errors.

////////////////////////////////

Bitwise operators in details

Bitwise Operators in Java

Last Updated : 13 Apr, 2026

Bitwise operators in Java are used to perform operations directly on the


binary representation (bits) of integer values. Instead of working on whole
numbers, these operators manipulate data bit by bit, enabling fast and
efficient low-level operations.

 Bitwise operators work only with integer data types such as byte,
short, int, long, and char

 They are commonly used in performance optimization, system


programming, and competitive coding

Let us now look at each bitwise operator and understand its working with
examples.

1. 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 shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)

2. Bitwise OR (|)

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 shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)

3. 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 shows
0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)

4. Bitwise Complement (~)

This operator is a unary operator, denoted by '~'. It inverts all the bits of the
given number (0 becomes 1 and 1 becomes 0).

Important: In Java, int is a 32-bit signed integer.

Example:
a=5

32-bit binary representation of 5:


00000000 00000000 00000000 00000101

After applying ~a (bitwise complement):


11111111 11111111 11111111 11111010

In decimal, this value is -6.


This is because in Java:

~N = -(N + 1)
So
~5 = -(5 + 1) = -6

Explanation: The bitwise complement operator ~ in Java inverts all 32 bits


of an integer.
For any integer N, the result of ~N is equal to:

~N = -(N + 1)

Therefore, ~5 = -(5 + 1) = -6.


Illustration: Here is a Java program demonstrating all bitwise operators.

public class TestClass {

public static void main(String[] args)

// Initial values

int a = 5;

int b = 7;

// bitwise and

// 0101 & 0111=0101 = 5

[Link]("a&b = " + (a & b));

// bitwise or

// 0101 | 0111=0111 = 7
[Link]("a|b = " + (a | b));

// bitwise xor

// 0101 ^ 0111=0010 = 2

[Link]("a^b = " + (a ^ b));

// bitwise not

// ~00000000 00000000 00000000 00000101=11111111 11111111


11111111 11111010

// will give 2's complement (32 bit) of 5 = -6

[Link]("~a = " + ~a);

// can also be combined with

// assignment operator to provide shorthand

// assignment

// a=a&b

a &= b;

[Link]("a= " + a);

Output

a&b = 5

a|b = 7

a^b = 2

~a = -6

a= 5

Bitwise Operators with Binary Output


class TestClass {

public static void main (String[] args) {

String binary[]={

"0000","0001","0010","0011","0100","0101",

"0110","0111","1000","1001","1010",

"1011","1100","1101","1110","1111"

};

// initializing the values of a and b

int a=3; // 0+2+1 or 0011 in binary

int b=6; // 4+2+0 or 0110 in binary

// bitwise or

int c= a | b;

// bitwise and

int d= a & b;

// bitwise xor

int e= a ^ b;

// bitwise not

int f= (~a & b)|(a &~b);

int g= ~a & 0x0f;


[Link](" a= "+binary[a]);

[Link](" b= "+binary[b]);

[Link](" a|b= "+binary[c]);

[Link](" a&b= "+binary[d]);

[Link](" a^b= "+binary[e]);

[Link]("~a & b|a&~b= "+binary[f]);

[Link]("~a= "+binary[g]);

Output

a= 0011

b= 0110

a|b= 0111

a&b= 0010

a^b= 0101

~a & b|a&~b= 0101

~a= 1100

Bit-Shift Operators (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.

Syntax:

number shift_op number_of_places_to_shift;

Types of Shift Operators

Shift Operators are further divided into 3 types. These are:

1. Signed Right shift operator (>>)

2. Unsigned Right shift operator (>>>)


3. Left shift operator(<<)

Note: For more detail about the Shift Operators in Java, refer Shift Operator
in Java.

Example: Program to Implement all Bitwise Operators in Java for User Input

import [Link];

public class TestClass {

public static void main(String[] args) {

Scanner input = new Scanner([Link]);

[Link]("Enter first number: ");

int num1 = [Link]();

[Link]("Enter second number: ");

int num2 = [Link]();

[Link]("Bitwise AND: " + (num1 & num2));

[Link]("Bitwise OR: " + (num1 | num2));

[Link]("Bitwise XOR: " + (num1 ^ num2));

[Link]("Bitwise NOT: " + (~num1));

[Link]("Bitwise Left Shift: " + (num1 << 2));

[Link]("Bitwise Right Shift: " + (num1 >> 2));

[Link]("Bitwise Unsigned Right Shift: " + (num1 >>> 2));

[Link]();

}
Input:

Enter first number: 4


Enter second number: 8

Output:

Bitwise AND: 0
Bitwise OR: 12
Bitwise XOR: 12
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1

Explanation: This program prompts the user to enter two numbers, num1
and num2. It then performs the following bitwise operations using the &, |, ^,
~, <<, >>, and >>> operators:

Comparision table

Operat
or Description

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

Bitwise Complement
~ (NOT)

<< Left Shift

>> Signed Right Shift


Operat
or Description

>>> Unsigned Right Shift

You might also like