0% found this document useful (0 votes)
24 views81 pages

2.java Mathematics - Operators

Uploaded by

robsonchungu5
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)
24 views81 pages

2.java Mathematics - Operators

Uploaded by

robsonchungu5
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
You are on page 1/ 81

MATHEMATICS OPERATORS

Operator: Operator in Java is a symbol that is used to perform operations. For


example: +, -, *, / etc.

Operators in Java
Java provides many types of operators which can be used according to the need.
They are classified based on the functionality they provide. Some of the types are-

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
10. Precedence and Associativity

Arithmetic Operators: They are used to perform simple arithmetic operations on primitive
data types.
 *: Multiplication
 /: Division
 %: Modulo
 +: Addition
 –: Subtraction
 Unary Operators: Unary operators need only one operand. They are used to increment,
decrement or negate a value.
 –: Unary minus, used for negating the values.
 +: Unary plus, indicates positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its
operand is byte, char, or short. This is called unary numeric promotion.
 ++: Increment operator, used for incrementing the value by 1. There are two
varieties of increment operator.
 Post-Increment: Value is first used for computing the result and
then incremented.
 Pre-Increment: Value is incremented first and then result is
computed.
 —: Decrement operator, used for decrementing the value by 1. There are two
varieties of decrement operator.
 Post-decrement: Value is first used for computing the result and
then decremented.
 Pre-Decrement: Value is decremented first and then result is
computed.
 !: Logical not operator, used for inverting a Boolean value.
 Assignment Operator: ‘=’ Assignment operator is used to assign a value to any variable.
It has a right to left associativity, i.e value given on right hand side of 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.
General format of assignment operator is,

variable = value;
 In many cases assignment operator can be combined with other operators to build a
shorter version of statement called Compound Statement. For example, instead of
a = a+5, we can write a += 5.
 +=, for adding left operand with right operand and then assigning it to
variable on the left.
 -=, for subtracting left operand with right operand and then assigning it to
variable on the left.
 *=, for multiplying left operand with right operand and then assigning it to
variable on the left.
 /=, for dividing left operand with right operand and then assigning it to
variable on the left.
 %=, for assigning modulo of left operand with right operand and then
assigning it to variable on the left.
 Relational Operators: These operators are used to check for relations like equality,
greater than, less than. They return Boolean result after the comparison and are
extensively used in looping statements as well as conditional if else statements. General
format is,

variable relation_operator value


 Some of the relational operators are-
 ==, Equal to: returns true if left hand side is equal to right hand side.
 ! =, Not Equal to : returns true if left hand side is not equal to right hand
side.
 <, less than: returns true if left hand side is less than right hand side.
 <=, less than or equal to: returns true if left hand side is less than or equal to
right hand side.
 >, Greater than: returns true if left hand side is greater than right hand side.
 >=, Greater than or equal to: returns true if left hand side is greater than or
equal to right hand side.
 Logical Operators: These operators are used to perform “logical AND” and “logical
OR” operation, i.e. the 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.
Conditional operators are-
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 Ternary operator: Ternary operator is a shorthand version of if-else statement. It has
three operands and hence the name ternary. 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 ‘:’.

// Java program to illustrate

// max of three numbers using

// ternary operator.
public class operators {

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
 Bitwise Operators: These operators are used to perform 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 Binary indexed tree.
 &, 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 complement representation of the input value, i.e. with all
bits inversed.
 Shift Operators: These 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. General format-
number shift_op number_of_places_to_shift;

<<, Left shift operator: shifts the bits of the number to the left and fills
0 on voids left as a result. Similar effect as of multiplying the number
with some power of two.
 >>, Signed Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit depends on
the sign of initial number. Similar effect as of dividing the number with
some power of two.
 >>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.
 instance of operator : 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. General format-

object instance of class/subclass/interface

// Java program to illustrate

// instance of operator

class operators {

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

}}

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 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 bottom shows the lowest precedence.

Interesting Questions on Operators

 Precedence and Associativity: There is often a confusion when it comes to hybrid


equations that is 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 same precedence,
solve according to associativity, that is either from right to left or from left to right.
Explanation of below program is well written in comments within the program itself .

public class operators {

public static void main(String[] args){

int a = 20, b = 10, c = 0, 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 precendence 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

Using + over (): When using + 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.

public class operators {

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

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

Java Arithmetic Operators with Examples


Operators constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to perform various
calculation and functions be it logical, arithmetic, relational etc. They are classified based on
the functionality they provide. Here are a few types:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators

Arithmetic Operators

These operators involve the mathematical operators that can be used to perform various
simple or advance arithmetic operations on the primitive data types referred to as the
operands. These operators consist of various unary and binary operators that can be applied
on a single or two operands respectively. Let’s look at the various operators that Java has to
provide under the arithmetic operators.

Now let’s look at each one of the arithmetic operators in Java:


1. Addition(+): This operator is a binary operator and is used to add two operands.
Syntax:
num1 + num2
Example:
num1 = 10, num2 = 20
sum = num1 + num2 = 30

// Java code to illustrate Addition operator

import java.io.*;

class Addition {

public static void main(String[] args){

// initializing variables

int num1 = 10, num2 = 20, sum = 0;

// Displaying num1 and num2

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// adding num1 and num2

sum = num1 + num2;

System.out.println("The sum = " + sum);

}}

Output:
num1 = 10
num2 = 20
The sum = 30
2. Subtraction(-): This operator is a binary operator and is used to subtract two
operands.
Syntax:
num1 - num2
Example:
num1 = 20, num2 = 10
sub = num1 - num2 = 10
// Java code to illustrate Subtraction operator

import java.io.*;

class Subtraction {

public static void main(String[] args){

// initializing variables

int num1 = 20, num2 = 10, sub = 0;

// Displaying num1 and num2

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// subtracting num1 and num2

sub = num1 - num2;

System.out.println("Subtraction = " + sub);

}}

Output:
num1 = 20
num2 = 10
Subtraction = 10
3. Multiplication(*): This operator is a binary operator and is used to multiply two
operands.
Syntax:
4. num1 * num2
Example:

num1 = 20, num2 = 10

mult = num1 * num2 = 200

// Java code to illustrate Multiplication operator


import java.io.*;

class Multiplication {

public static void main(String[] args){

// initializing variables

int num1 = 20, num2 = 10, mult = 0;

// Displaying num1 and num2

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// Multiplying num1 and num2

mult = num1 * num2;

System.out.println("Multiplication = " + mult);

}}

Output:
num1 = 20
num2 = 10
Multiplication = 200
5. Division(/): This is a binary operator that is used to divide the first
operand(dividend) by the second operand(divisor) and give the quotient as
result.
Syntax:
num1 / num2
Example:

num1 = 20, num2 = 10

div = num1 / num2 = 2

// Java code to illustrate Division operator


import java.io.*;

class Division {

public static void main(String[] args){

// initializing variables

int num1 = 20, num2 = 10, div = 0;

// Displaying num1 and num2

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// Dividing num1 and num2

div = num1 / num2;

System.out.println("Division = " + div);

}}

Output:
num1 = 20
num2 = 10
Division = 2
6. Modulus(%): This is a binary operator that is used to return the remainder
when the first operand(dividend) is divided by the second operand(divisor).
Syntax:
num1 % num2
Example:

num1 = 5, num2 = 2

mod = num1 % num2 = 1

// Java code to illustrate Modulus operator


import java.io.*;

class Modulus {

public static void main(String[] args){

// initializing variables

int num1 = 5, num2 = 2, mod = 0;

// Displaying num1 and num2

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// Remaindering num1 and num2

mod = num1 % num2;

System.out.println("Remainder = " + mod);

Output:
num1 = 5
num2 = 2
Remainder = 1
7. Increment (++): This is a unary operator that acts on one operand, unlike the
previous operations. It is used to increment the value of an integer. It can be
used in two ways:
1. Post-increment operator: When placed after the variable name, the
value of the operand is incremented but the previous value is retained
temporarily until the execution of this statement and it gets updated
before the execution of the next statement.
Syntax:
num++
Example:
1.
a. num = 5
b. num++ = 6
c. Pre-increment operator: When placed before the variable name, the operand’s
value is incremented instantly.
Syntax:
++num
Example:
num = 5
++num = 6

// Java code to illustrate increment operator

import java.io.*;

class Increment {

public static void main(String[] args){

// initializing variables

int num = 5;

// first 5 gets printed and then

// increment to 6

System.out.println("Post "

+ "increment = " + num++);

// num was 6, incremented to 7

// then printed

System.out.println("Pre "

+ "increment = " + ++num);

}}

2. Output:
3. Post increment = 5
4. Pre increment = 7
5. Decrement(–): This is also a unary operator that acts on one operand. It is used to
decrement the value of an integer. It can be used in two ways:
a. Post-decrement operator: When placed after the variable name, the value of
the operand is decremented but the previous values is retained temporarily
until the execution of this statement and it gets updated before the execution
of the next statement.
Syntax:
num--
Example:
num = 5
num-- = 4
b. Pre-decrement operator: When placed before the variable name, the operand’s
value is decremented instantly.
Syntax:
--num
Example:
num = 5
--num = 4

// Java code to illustrate decrement operator

import java.io.*;

class Decrement {

public static void main(String[] args){

// initializing variables

int num = 5;

// first 5 gets printed and then

// decremented to 4

System.out.println("Post + "decrement = " + num--);

System.out.println("num = " + num);

// num was 4, decremented to 3


// then printed

System.out.println("Pre "

+ "decrement = " + --num);

}}

6. Output:
7. Post decrement = 5
8. num = 4
9. Pre decrement = 3

Java Assignment Operator with Examples


Operators constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to perform various
calculation and functions be it logical, arithmetic, relational etc. They are classified based on
the functionality they provide. Here are a few types:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators

Assignment Operators
These operators are used to assign values to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data-type of the operand on the left
side otherwise the compiler will raise an error. This means that the assignment operators
have 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 assignment operator is,
variable operator value;
Let’s look at each of the assignment operators and how they operate:
1. “=”: This is the simplest assignment operator which is used to assign the value on
the right to the variable on the left. This is the basic definition of assignment
operator and how does it functions.
Syntax:
num1 = num2;
Example:
a = 10;
ch = 'y';

// Java code to illustrate "="

import java.io.*;

class Assignment {

public static void main(String[] args){

// Declaring variables

int num;

String name;

// Assigning values

num = 10;

name = "GeeksforGeeks";

// Displaying the assigned values

System.out.println("num is assigned: " + num);

System.out.println("name is assigned: " + name);

}}

Output:
num is assigned: 10
name is assigned: GeeksforGeeks
Note: In many cases, the assignment operators can be combined with other operators to
build a shorter version of the statement called Compound Statement. For example,
instead of a = a+5, we can write a += 5. Let’s look at similar assignment operators that
form the compound statements.
2. “+=”: This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the
current value of the variable on left to the value on the right and then assigning the
result to the operand on the left.
Syntax:
num1 += num2;
Example:
a += 10
This means,
a = a + 10

// Java code to illustrate "+="

import java.io.*;

class Assignment {

public static void main(String[] args){

// Declaring variables

int num1 = 10, num2 = 20;

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// Adding & Assigning values

num1 += num2;

// Displaying the assigned values

System.out.println("num1 = " + num1);

Output:
num1 = 10
num2 = 20
num1 = 30
1. 30
2.
3. “-=”: This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting
the value of the variable on right from the current value of the variable on the left and
then assigning the result to the operand on the left.
Syntax:
num1 -= num2;
Example:
a -= 10

This means,
a = a - 10

// Java code to illustrate "-="

import java.io.*;

class Assignment {

public static void main(String[] args){

// Declaring variables

int num1 = 10, num2 = 20;

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// Subtracting & Assigning values

num1 -= num2;

// Displaying the assigned values

System.out.println("num1 = " + num1);

}}

Output:
num1 = 10
num2 = 20
num1 = -10
4. “*=”: This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying
the current value of the variable on left to the value on the right and then assigning the
result to the operand on the left.
Syntax:
num1 *= num2;
Example:
a *= 10
This means,
a = a * 10

// Java code to illustrate "*="

import java.io.*;

class Assignment {

public static void main(String[] args){

// Declaring variables

int num1 = 10, num2 = 20;

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// Multiplying & Assigning values

num1 *= num2;

// Displaying the assigned values

System.out.println("num1 = " + num1);

Output:
num1 = 10
num2 = 20
num1 = 200
5. “/=”: This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the
current value of the variable on left by the value on the right and then assigning the
quotient to the operand on the left.
Syntax:
num1 /= num2;
Example:
a /= 10
This means,
a = a / 10
// Java code to illustrate "/="

import java.io.*;

class Assignment {

public static void main(String[] args){

// Declaring variables

int num1 = 20, num2 = 10;

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// Dividing & Assigning values

num1 /= num2;

// Displaying the assigned values

System.out.println("num1 = " + num1);

Output:
num1 = 20
num2 = 10
num1 = 2
6. “%=”: This operator is a compound of ‘%’ and ‘=’ operators. It operates by
dividing the current value of the variable on left by the value on the right and
then assigning the remainder to the operand on the left.
Syntax:
num1 %= num2;
Example:
a %= 3

This means,
a=a%3

// Java code to illustrate "%="

import java.io.*;

class Assignment {

public static void main(String[] args){

// Declaring variables

int num1 = 5, num2 = 3;

System.out.println("num1 = " + num1);

System.out.println("num2 = " + num2);

// Moduling & Assigning values

num1 %= num2;

// Displaying the assigned values

System.out.println("num1 = " + num1);

Output:
num1 = 5
num2 = 3
num1 = 2

Java Unary Operator with Examples


Operators constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to perform various
calculation and functions be it logical, arithmetic, relational etc. They are classified based on
the functionality they provide. Here are a few types:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
This article explains all that one needs to know regarding the Unary Operators.
Unary Operators in Java
Java unary operators are the types that need only one operand to perform any operation like
increment, decrement, negation etc. It consists of various arithmetic, logical and other
operators that operate on a single operand. Let’s look at the various unary operators in
detail and see how they operate.
1. Unary minus(-): This operator can be used to convert a negative value to a positive one.
Syntax:
-(operand)
Example:
a = -10
Below is the program to illustrate Java unary – operator.

// Java code to illustrate unary -

import java.io.*;

class Unary {

public static void main(String[] args){

// variable declaration

int n1 = 20;

System.out.println("Number = " + n1);

// Performing unary operation

n1 = -n1;

// Print the result number

System.out.println("Result = " + n1);

}}

Output:
Number = 20
Result = -20
2. ‘NOT’ Operator(!): This is used to convert true to false or vice versa. Basically it
reverses the logical state of an operand.
Syntax:
!(operand)
Example:
cond = !true;

// cond < false

Below is the program to illustrate Java unary ! operator.

// Java code to illustrate

// unary NOT operator

import java.io.*;

class Unary {

public static void main(String[] args){

// initializing variables

boolean cond = true;

int a = 10, b = 1;

// Displaying cond, a, b

System.out.println("Cond is: " + cond);

System.out.println("Var1 = " + a);

System.out.println("Var2 = " + b);

// Using unary NOT operator

System.out.println("Now cond is: " + !cond);

System.out.println("!(a < b) = " + !(a < b));

System.out.println("!(a > b) = " + !(a > b));

}
}

Output:
1. Cond is: true
2. Var1 = 10
3. Var2 = 1
4. Now cond is: false
5. ! (a < b) = true
6. ! (a > b) = false
7.
8. Increment (++): It is used to increment the value of an integer. It can be used in
two separate ways:
a. Post-increment operator: When placed after the variable name, the value of the
operand is incremented but the previous value is retained temporarily until the
execution of this statement and it gets updated before the execution of the next
statement.
Syntax:
num++
Example:
num = 5
num++ = 6
b. Pre-increment operator: When placed before the variable name, the operand’s
value is incremented instantly.
Syntax:
++num
Example:
num = 5
++num = 6

Below is the program to illustrate Java unary Increment(++) operator.

// Java code to illustrate increment operator

import java.io.*;

class Unary {

public static void main(String[] args){


// initializing variables

int num = 5;

// first 5 gets printed and then

// increment to 6

System.out.println("Post "

+ "increment = " + num++);

// num was 6, incremented to 7

// then printed

System.out.println("Pre "

+ "increment = " + ++num);

}}

9. Output:
Post increment = 5
Pre increment = 7
10. Decrement (--): It is used to decrement the value of an integer. It can be used in
two separate ways:
a. Post-decrement operator: When placed after the variable name, the value of the
operand is decremented but the previous values is retained temporarily until the
execution of this statement and it gets updated before the execution of the next
statement.
Syntax:
num--
Example:
num = 5
num-- = 4
b. Pre-decrement operator: When placed before the variable name, the operand’s
value is decremented instantly.
Syntax:
--num
Example:
num = 5
--num = 4
11. Below is the program to illustrate Java unary Decrement(--) operator.

// Java code to illustrate decrement operator

import java.io.*;

class Unary {

public static void main(String[] args){

// initializing variables

int num = 5;

// first 5 gets printed and then

// decremented to 4

System.out.println("Post "

+ "decrement = " + num--);

System.out.println("num = " + num);

// num was 4, decremented to 3

// then printed

System.out.println("Pre "

+ "decrement = " + --num);

}}

Output:
Post decrement = 5
num = 4
Pre decrement = 3

 Bitwise Complement(~): This unary operator returns the one’s complement


representation of the input value or operand, i.e, with all bits inverted, means it makes every 0
to 1, and every 1 to 0.
Syntax:
~(operand)
Example:
a = 5 [0101 in Binary]
result = ~5

This performs a bitwise complement of 5


~0101 = 1010 = 10 (in decimal)
Then the compiler will give 2’s complement
of that number.
2’s complement of 10 will be -6.
result = -6
Below is the program to illustrate Java unary ~ operator.

// Java code to illustrate unary ~

import java.io.*;

class Unary {

public static void main(String[] args){

// variable declaration

int n1 = 6, n2 = -2;

// Displaying numbers

System.out.println("First Number = " + n1);

System.out.println("Second Number = " + n2);

// Performing bitwise complement

System.out.println(n1 + "'s bitwise complement = " + ~n1);

System.out.println(n2 + "'s bitwise complement = " + ~n2);

}}

Output:
First Number = 6
Second Number = -2
6's bitwise complement = -7
-2's bitwise complement = 1
Java Relational Operators with Examples
Operators constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to perform
various calculations and functions be it logical, arithmetic, relational, etc. They are
classified based on the functionality they provide.
Types of Operators:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
Relational Operators are a bunch of binary operators that are used to check for
relations between two operands including equality, greater than, less than, etc. They
return a Boolean result after the comparison and are extensively used in looping
statements as well as conditional if-else statements and so on. The general format of
representing relational operator is:
Syntax:

ariable1 relation_operator variable2


Let us look at each one of the relational operators in Java:
Operator 1: ‘Equal to’ operator (==)
This operator is used to check whether the two given operands are equal or not. The
operator returns true if the operand at the left-hand side is equal to the right-hand
side, else false.
Syntax:
var1 == var2
Illustration:
var1 = "GeeksforGeeks"
var2 = 20
var1 == var2 results in false
Example:

// Java Program to Illustrate equal to Operator

// Importing I/O classes

import java.io.*;

// Main class

class GFG {
// Main driver method

public static void main(String[] args){

// Initializing variables

int var1 = 5, var2 = 10, var3 = 5;

// Displaying var1, var2, var3

System.out.println("Var1 = " + var1);

System.out.println("Var2 = " + var2);

System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and

// printing corresponding boolean value

System.out.println("var1 == var2: "

+ (var1 == var2));

// Comparing var1 and var3 and

// printing corresponding boolean value

System.out.println("var1 == var3: "

+ (var1 == var3));

}}

Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: false
var1 == var3: true
Operator 2: ‘Not equal to’ Operator (!=)
This operator is used to check whether the two given operands are equal or not. It
functions opposite to that of the equal-to-operator. It returns true if the operand at
the left-hand side is not equal to the right-hand side, else false.

Syntax:
var1!= var2
Illustration:
var1 = "GeeksforGeeks"
var2 = 20
var1 != var2 results in true
Example

// Java Program to Illustrate No- equal-to Operator

// Importing I/O classes

import java.io.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args){

// Initializing variables

int var1 = 5, var2 = 10, var3 = 5;

// Displaying var1, var2, var3

System.out.println("Var1 = " + var1);

System.out.println("Var2 = " + var2);

System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and

// printing corresponding boolean value


System.out.println("var1 == var2: "

+ (var1 != var2));

// Comparing var1 and var3 and

// printing corresponding boolean value

System.out.println("var1 == var3: "

+ (var1 != var3));

}}

Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: true
var1 == var3: false
Operator 3: Greater than’ operator(>)
This checks whether the first operand is greater than the second operand or not. The
operator returns true when the operand at the left-hand side is greater than the right-
hand side.
Syntax:
var1 > var2
Illustration:
var1 = 30
var2 = 20
var1 > var2 results in true

Example:

// Java code to Illustrate Greater than operator

// Importing I/O classes

import java.io.*;
// Main class

class GFG {

// Main driver method

public static void main(String[] args){

// Initializing variables

int var1 = 30, var2 = 20, var3 = 5;

// Displaying var1, var2, var3

System.out.println("Var1 = " + var1);

System.out.println("Var2 = " + var2);

System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and

// printing corresponding boolean value

System.out.println("var1 > var2: " + (var1 > var2));

// Comparing var1 and var3 and

// printing corresponding boolean value

System.out.println("var3 > var1: "

+ (var3 >= var1));

}}

Output
Var1 = 30
Var2 = 20
Var3 = 5
var1 > var2: true
var3 > var1: false
Operator 4: Less than’ Operator(<)
This checks whether the first operand is less than the second operand or not. The operator
returns true when the operand at the left-hand side is less than the right-hand side. It
functions opposite to that of the greater-than operator.

Syntax:
var1 < var2
Illustration:
var1 = 10
var2 = 20
var1 < var2 results in true

// Java code to Illustrate Less than Operator

// Importing I/O classes

import java.io.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args){

// Initializing variables

int var1 = 10, var2 = 20, var3 = 5;

// Displaying var1, var2, var3

System.out.println("Var1 = " + var1);

System.out.println("Var2 = " + var2);

System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and

// printing corresponding boolean value

System.out.println("var1 < var2: " + (var1 < var2));

// Comparing var2 and var3 and


// printing corresponding boolean value

System.out.println("var2 < var3: " + (var2 < var3));

}}

Output
Var1 = 10
Var2 = 20
Var3 = 5
var1 < var2: true
var2 < var3: false
Operator 5: Greater than or equal to (>=)
This checks whether the first operand is greater than or equal to the second operand or not.
The operator returns true when the operand at the left-hand side is greater than or equal to
the right-hand side.
Syntax:

var1 >= var2


Illustration:
var1 = 20
var2 = 20
var3 = 10
var1 >= var2 results in true
var2 >= var3 results in true
Example:

// Java Program to Illustrate Greater than or equal to

// Operator

// Importing I/O classes

import java.io.*;

// Main class

class GFG {
// Main driver method

public static void main(String[] args){

// Initializing variables

int var1 = 20, var2 = 20, var3 = 10;

// Displaying var1, var2, var3

System.out.println("Var1 = " + var1);

System.out.println("Var2 = " + var2);

System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and

// printing corresponding boolean value

System.out.println("var1 >= var2: "

+ (var1 >= var2));

// Comparing var2 and var3 and

// printing corresponding boolean value

System.out.println("var2 >= var3: "

+ (var3 >= var1));

}}

Output
Var1 = 20
Var2 = 20
Var3 = 10
var1 >= var2: true
var2 >= var3: false
Operator 6: Less than or equal to (<=)
This checks whether the first operand is less than or equal to the second operand or not. The
operator returns true when the operand at the left-hand side is less than or equal to the right-
hand side.
Syntax:
var1 <= var2
Illustration:
var1 = 10
var2 = 10
var3 = 9
var1 <= var2 results in true
var2 <= var3 results in false
Example:

// Java Program to Illustrate Less

// than or equal to operator

// Importing I/O classes

import java.io.*;

// Main class

class GFG {

// Main driver method

public static void main(String[] args){

// Initializing variables

int var1 = 10, var2 = 10, var3 = 9;

// Displaying var1, var2, var3

System.out.println("Var1 = " + var1);

System.out.println("Var2 = " + var2);

System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and

// printing corresponding boolean value

System.out.println("var1 <= var2: "


+ (var1 <= var2));

// Comparing var2 and var3 and

// printing corresponding boolean value

System.out.println("var2 <= var3: "

+ (var2 <= var3));

}}

Output
Var1 = 10
Var2 = 10
Var3 = 9
var1 <= var2: true
var2 <= var3: false

Java Logical Operators with Examples


Operators constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to perform various
calculation and functions be it logical, arithmetic, relational etc. They are classified based on
the functionality they provide. Here are a few types:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
This article explains all that one needs to know regarding the Logical Operators.
Logical Operators
These operators are used to perform logical “AND”, “OR” and “NOT” operation, i.e. the
function similar to AND gate and OR gate in digital electronics. They are used to combine
two or more conditions/constraints or to complement the evaluation of the original
condition under particular consideration. 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. Let’s look at each of the logical
operators in a detailed manner:
1. ‘Logical AND’ Operator(&&): This operator returns true when both the conditions
under consideration are satisfied or are true. If even one of the two yields false, the
operator results false. For example, cond1 && cond2 returns true when both cond1 and
cond2 are true (i.e. non-zero).
Syntax:
condition1 && condition2
Example:
a = 10, b = 20, c = 20
condition1: a < b
condition2: b == c
if(condition1 && condition2)
d = a+b+c
// Since both the conditions are true
d = 50.

// Java code to illustrate

// logical AND operator

import java.io.*;

class Logical {

public static void main(String[] args){

// initializing variables

int a = 10, b = 20, c = 20, d = 0;

// Displaying a, b, c

System.out.println("Var1 = " + a);

System.out.println("Var2 = " + b);

System.out.println("Var3 = " + c);

// using logical AND to verify

// two constraints

if ((a < b) && (b == c)) {

d = a + b + c;

System.out.println("The sum is: " + d);

}
else

System.out.println("False conditions");

}}

Output:
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50
2. 'Logical OR' Operator(||): This operator returns true when one of the two conditions
under consideration are satisfied or are true. If even one of the two yields true, the
operator results true. To make the result false, both the constraints need to return false.
Syntax:
condition1 || condition2
Example:
a = 10, b = 20, c = 20
condition1: a < b
condition2: b > c

if(condition1 || condition2)
d = a+b+c

// Since one of the condition is true


d = 50.

// Java code to illustrate

// logical OR operator

import java.io.*;

class Logical {

public static void main(String[] args){

// initializing variables
int a = 10, b = 1, c = 10, d = 30;

// Displaying a, b, c

System.out.println("Var1 = " + a);

System.out.println("Var2 = " + b);

System.out.println("Var3 = " + c);

System.out.println("Var4 = " + d);

// using logical OR to verify

// two constraints

if (a > b || c == d)

System.out.println("One or both"

+ " the conditions are true");

else

System.out.println("Both the"

+ " conditions are false");

Output:
Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both the conditions are true
3. 'Logical NOT' Operator(!): Unlike the previous two, this is a unary operator and returns
true when the condition under consideration is not satisfied or is a false condition.
Basically, if the condition is false, the operation returns true and when the condition is
true, the operation returns false.
Syntax:
!(condition)
Example:
a = 10, b = 20

!(a<b) // returns false

!(a>b) // returns true

// Java code to illustrate

// logical NOT operator

import java.io.*;

class Logical {

public static void main(String[] args){

// initializing variables

int a = 10, b = 1;

// Displaying a, b, c

System.out.println("Var1 = " + a);

System.out.println("Var2 = " + b);

// Using logical NOT operator

System.out.println("!(a < b) = " + !(a < b));

System.out.println("!(a > b) = " + !(a > b));

}}

Output:
Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false

 Java Ternary Operator with Examples021


Operators constitute the basic building block to any programming language. Java too
provides many types of operators which can be used according to the need to perform
various calculation and functions be it logical, arithmetic, relational etc. They are
classified based on the functionality they provide. Here are a few types:

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
This article explains all that one needs to know regarding the Ternary Operator.

Ternary Operator
Java ternary operator is the only conditional operator that takes three operands. It’s a
one-liner replacement for if-then-else statement and used a lot in Java programming.
We can use the ternary operator in place of if-else conditions or even switch
conditions using nested ternary operators. Although it follows the same algorithm as
of if-else statement, the conditional operator takes less space and helps to write the if-
else statements in the shortest way possible.

Syntax:

variable = Expression1? Expression2: Expression3


If operates similarly to that of the if-else statement as in Exression2 is executed
if Expression1 is true else Expression3 is executed.

if(Expression1){
variable = Expression2;
}
else{
variable = Expression3;
}
Example:

num1 = 10;
num2 = 20;
res=(num1>num2)? (num1+num2):(num1-num2)
Since num1<num2,
the second operation is performed
res = num1-num2 = -10
Flowchart of Ternary Operation

Example 1:

// Java program to find largest among two

// numbers using ternary operator

import java.io.*;

class Ternary {

public static void main(String[] args){

// variable declaration

int n1 = 5, n2 = 10, max;


System.out.println("First num: " + n1);

System.out.println("Second num: " + n2);

// Largest among n1 and n2

max = (n1 > n2) ? n1 : n2;

// Print the largest number

System.out.println("Maximum is = " + max);

}}

Output:
First num: 5
Second num: 10
Maximum is = 10
Example 2:

// Java code to illustrate ternary operator

import java.io.*;

class Ternary {

public static void main(String[] args){

// variable declaration

int n1 = 5, n2 = 10, res;

System.out.println("First num: " + n1);

System.out.println("Second num: " + n2);

// Performing ternary operation

res = (n1 > n2)? (n1 + n2) : (n1 - n2);

// Print the largest number


System.out.println("Result = " + res);

}}

Output:
First num: 5
Second num: 10
Result = -5

Bitwise operators in Java


Bitwise operators are used to performing manipulation of individual bits of a number. They
can be used with any of the integral types (char, short, int, etc). They are used when
performing update and query operations of Binary indexed tree.
 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 gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
 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 gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111
________
0101 = 5 (In decimal)
 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 gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR Operation of 5 and 7
0101
^ 0111
________
0010 = 2 (In decimal)
 Bitwise Complement (~) –
This operator is a unary operator, denoted by ‘~’. It returns the one’s complement
representation of the input value, i.e, with all bits inverted, which means it makes
every 0 to 1, and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)
Bitwise Complement Operation of 5
~ 0101
________
1010 = 10 (In decimal)
 Note – Compiler will give 2’s complement of that number, i.e., 2’s complement of
10 will be -6.

// Java program to illustrate

// bitwise operators

public class operators {

public static void main(String[] args){

// Initial values

int a = 5;

int b = 7;

// bitwise and

// 0101 & 0111=0101 = 5

System.out.println("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7

System.out.println("a|b = " + (a | b));

// bitwise xor

// 0101 ^ 0111=0010 = 2

System.out.println("a^b = " + (a ^ b));

// bitwise not

// ~0101=1010

// will give 2's complement of 1010 = -6

System.out.println("~a = " + ~a);

// can also be combined with

// assignment operator to provide shorthand

// assignment

// a=a&b

a &= b;

System.out.println("a= " + a);

Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Shift Operators: These 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. General format:
number shift_op number_of_places_to_shift;
 Signed Right shift operator (>>) –
Shifts the bits of the number to the right and fills the voids left with the sign bit (1 in case
of negative number and 0 in case of positive number). The leftmost bit and a depends on
the sign of initial number. Similar effect as of dividing the number with some power of
two.
For example,
Example 1:
a = 10
a>>1 = 5

Example 2:
a = -10
a>>1 = -5
We preserve the sign bit.
 Unsigned Right shift operator (>>>) –
Shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost
bit is set to 0. (>>>) is unsigned-shift; it’ll insert 0. (>>) is signed, and will extend the
sign bit.
For example,
Example 1:
a = 10
a>>>1 = 5

Example 2:
a = -10
a>>>1 = 2147483643
DOES NOT preserve the sign bit.
 Left shift operator (<<) –
Shifts the bits of the number to the left and fills 0 on voids left as a result. Similar
effect as of multiplying the number with some power of two.
For example,
a = 5 = 0000 0101
b = -10 = 1111 0110
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40

Unsigned Left shift operator (<<<) –


Unlike unsigned Right Shift, there is no “<<<” operator in Java, because the logical (<<) and
arithmetic left-shift (<<<) operations are identical.

// Java program to illustrate

// shift operators

public class operators {

public static void main(String[] args){

int a = 5;

int b = -10;

// left shift operator

// 0000 0101<<2 =0001 0100(20)

// similar to 5*(2^2)

System.out.println("a<<2 = " + (a << 2));

// right shift operator

// 0000 0101 >> 2 =0000 0001(1)

// similar to 5/(2^2)

System.out.println("b>>2 = " + (b >> 2));

// unsigned right shift operator

System.out.println("b>>>2 = " + (b >>> 2));

}}

Output
a<<2 = 20
b>>2 = -3
b>>>2 = 1073741821

An operator is a symbol that operates on one or more operands to produce a result.


 && This means that IF we have two condition the resulting condition is true
then both CONDITION are true[yes][yes].
 | | True, if either condition is true [yes] [yes].
 ! Negative: makes true out of false [x] [yes].

1. AND && OR ||
int x, y; // && = AND This is a shorthand

x = 10; // ||= OR Both conditions must be true for AND to work

y = -10; // So, it first checks the condition on the left, if satisfied, then
checks on the right-hand side.

// You can also use a Single & and single |.

if(x>0 && y>0){


System.out.println("Both nums are +ve");
}else if(x>0|| y>0){
System.out.println(At leats one num is +ve");
}else{
System.out.println("Both nums are -ve");
}

1. Java Variable Example: Add Two Numbers

public class Simple{


public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}

Output: 20

Java Variable Example: Widening

public class Simple{


1. public static void main(String[] args){
2. int a=10;
3. float f=a;
4. System.out.println(a);
5. System.out.println(f);
6. }
7. }

Output:
10
10.0

Java Variable Example: Narrowing (Typecasting)

1.
public class Simple{
2.
public static void main(String[] args){
3.
float f=10.5f;
4.
//int a=f;//Compile time error
5.
int a=(int)f;
6.
System.out.println(f);
7.
System.out.println(a);
}
}
Output:
10
10.0

Java Variable Example: Overflow


1.
class Simple{
2.
public static void main(String[] args){
3.
//Overflow
4.
int a=130;
5.
byte b=(byte)a;
6.
System.out.println(a);
7.
System.out.println(b);
}
}
Output: 130
-126

Java Variable Example:


Adding Lower Type
class Simple{
2. public static void main(String[] args){
3. byte a=10;
4. byte b=10;
5. //byte c=a+b; //Compile Time Error: because a+b = 20 will be int
6. byte c=(byte)(a+b);
7. System.out.println(c);
8. }
}
Output: 20

Java - Basic Operators


Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misceneous Operators
OPERATORS IN JAVA

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


1. public class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }
9. }

Output:
10

12

12

10

Java Unary Operator Example 2: ++ and --


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a); //10+12=22
6. System.out.println(b++ + b++); //10+11=21
7. }
8. }

Output:
22

21

Java Unary Operator Example: ~ and !


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);
//11 (minus of total positive value which starts from 0)
8. System.out.println(~b);
//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c); //false (opposite of boolean value)
10.System.out.println(!d); //true
11.}}

Output:

-11

false

true

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0

}}
Output:
15

50

Java Arithmetic Operator Example: Expression


1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }
5. }

Output:

21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left
side of a specified number of times.

Java Left Shift Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2); //10*2^2=10*4=40
4. System.out.println(10<<3); //10*2^3=10*8=80
5. System.out.println(20<<2); //20*2^2=20*4=80
6. System.out.println(15<<4); //15*2^4=15*16=240
7. }
8. }

Output:
40
80

80

240

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to
right by the number of bits specified by the right operand.

Java Right Shift Operator Example


1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}

Output:
2

Java Shift Operator Example: >> vs >>>


1. public class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}
Output:
5

-5

1073741819

Java AND Operator


Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first
condition is false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is
true or false.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c); //false && true = false
7. System.out.println(a<b&a<c); //false & true = false
8. }}

Output:
false

false

Java AND Operator Example:


Logical && vs Bitwise &
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10.}}

Output:
false

10

false

11

Java OR Operator Example:


Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is
true. It checks the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is
true or false.

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10.System.out.println(a);//10 because second condition is not checked
11.System.out.println(a>b|a++<c);//true | true = true
12.System.out.println(a);//11 because second condition is checked
13.}}

Output:
true

true

true

10

true

11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement
and used a lot in Java programming. It is the only conditional operator which
takes three operands.

Java Ternary Operator Example

1. public class OperatorExample{


2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

Another Example:
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }
8. }

Output:

Java Assignment Operator


Java assignment operator is one of the most common operators. It is
used to assign the value on its right to the operand on its left.

Java Assignment Operator Example


1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}

Output:
14

16

Java Assignment Operator Example


1. public class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10.a/=2;//18/2
11.System.out.println(a);
12.}}

Output:
13

18

Java Assignment Operator Example:

Adding short

1. public class OperatorExample{


2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}

Output:
Compile time error

After type cast:


1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}

Output: 20

The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:

Assume integer variable A holds 10 and variable B holds 20, then:

Operator and Example


Sr.No.
+ (Addition)

1 Adds values on either side of

the operator

Example: A + B will give 30

- (Subtraction)
Subtracts right-hand operand from left-hand operand
2
Example: A - B will give -10

* (Multiplication)
Multiplies values on either side of the operator
3
Example: A * B will give 200
/ (Division)
Divides left-hand operand by right-hand operand
4
Example: B / A will give 2

% (Modulus)
Divides left-hand operand by right-hand operand and returns remainder
5
Example: B % A will give 0

++ (Increment)

6 Increases the value of operand by 1

Example: B++ gives 21


-- (Decrement)

Decreases the value of operand by 1


7 Example: B-- gives 19

Example
The following program is a simple example which demonstrates the arithmetic operators.
Copy and paste the following Java program in Test.java file, and compile and run this
program:

public class Test {


public static void main (String args[]) {
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b)); System.out.println("a -
b = " + (a - b)); System.out.println("a * b = " + (a * b));
System.out.println("b / a = " + (b / a));
System.out.println("b % a = " + (b % a));
System.out.println("c % a = " + (c % a));
System.out.println("a++ = " + (a++));
System.out.println("b-- = " + (a--));
Check the difference in d++ and ++d
System.out.println("d++ = " + (d++));
System.out.println("++d = " + (++d));
}}

This will produce the following result:

a + b = 30
- b = -10
* b = 200
/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27

The Relational Operators


There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then:

Sr. No. Operator and Description

== (equal to)

Checks if the values of two operands are equal or not, if yes then condition
1 becomes true.

Example: (A == B) is not true.

!= (not equal to)

Checks if the values of two operands are equal or not, if values are not
2 equal then condition becomes true.

Example: (A != B) is true.
> (greater than)

Checks if the value of left operand is greater than the value of right
operand, if yes then condition becomes true.

Example: (A > B) is not true.

< (less than)


Checks if the value of left operand is less than the value of right
operand, if yes then condition becomes true.
Example: (A < B) is true.

>= (greater than or equal to)


Checks if the value of left operand is greater than or equal to the
value of right operand, if yes then condition becomes true.

Example: (A >= B) is not true.


<= (less than or equal to)
Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true.

Example: (A <= B) is true.

Example
The following program is a simple example that demonstrates the relational operators. Copy
and paste the following Java program in Test.java file and compile and run this program.

public class Test {

public static void main (String args []) {


int a = 10;
int b = 20;
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("b >= a = " + (b >= a));
System.out.println("b <= a = " + (b <= a));
}}
This will produce the following result:

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

The Bitwise Operators


Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a = 60 and b = 13; now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators:


Assume integer variable A holds 60 and variable B holds 13 then:
Sr. No. Operator and Description

& (bitwise and)


1
Binary AND Operator copies a bit to the result if it exists in both operands.

Example: (A & B) will give 12 which is 0000 1100


\

| (bitwise or)
Binary OR Operator copies a bit if it exists in either operand.
2
Example: (A | B) will give 61 which is 0011 1101

^ (bitwise XOR)
Binary XOR Operator copies the bit if it is set in one operand but not
both.
3
Example: (A ^ B) will give 49 which is 0011 0001

~ (bitwise compliment)

Binary Ones Complement Operator is unary and has the effect of 'flipping'
4 bits.

Example: (~A) will give -61 which is 1100 0011 in 2's complement form due to a
signed binary number.

<< (left shift)


5 Binary Left Shift Operator. The left operands value is moved left by the
number of bits specified by the right operand.

Example: A << 2 will give 240 which is 1111 0000

>> (right shift)

6 Binary Right Shift Operator. The left operands value is moved right
by the number of bits specified by the right operand.

Example: A >> 2 will give 15 which is 1111

>>> (zero fill right shift)


Shift right zero fill operator. The left operands value is moved right by the
number of bits specified by the right operand and shifted values are filled up
with zeros.

Example: A >>>2 will give 15 which is 0000 1111


Example
The following program is a simple example that demonstrates the bitwise operators. Copy and paste
the following Java program in Test.java file and compile and run this program:

public class Test {

public static void main (String args[]) {


int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 00001100 */
System.out.println("a &b=" +c );

c = a | b; /* 61 = 00111101 */
System.out.println("a |b=" +c );

c = a ^ b; /* 49 = 00110001 */
System.out.println("a ^b=" +c );

c = ~a; /*-61 = 11000011 */


System.out.println("~a =" + c );

c = a << 2; /* 240 = 11110000 */


System.out.println("a << 2 = " + c );

c = a >> 2; /* 15= 1111 */


System.out.println("a >> 2 = " + c );

c = a >>> 2; /* 15 = 0000 1111 */


System.out.println("a >>> 2 = " + c );
}}
This will produce the following result:

a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 15
a >>> 15

The Logical Operators


The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:

Operator Description

&& (logical and)


1
Called Logical AND operator. If both the operands are non-zero, then the
condition becomes true.
Example: (A && B) is false.

|| (logical or)

Called Logical OR Operator. If any of the two operands are non-zero, then
2
the condition becomes true.

Example: (A || B) is true.

! (logical not)

Called Logical NOT Operator. Use to reverses the logical state of its
operand. If a condition is true then Logical NOT operator will make false.

Example: !(A && B) is true.


Example
The following simple example program demonstrates the logical operators. Copy and paste
the following Java program in Test.java file and compile and run this program:

public class Test {

public static void main(String args[]) {


boolean a = true;
boolean b = false;

System.out.println("a && b = " + (a&&b));

System.out.println("a || b = " + (a||b) );

System.out.println("!(a && b) = " + !(a && b));


}}

This will produce the following result:

a && b = false
a || b = true
!(a && b) = true

The Assignment Operators


Following are the assignment operators supported by Java language:
Sr. No. Operator and Description

=
1
Simple assignment operator. Assigns values from right side operands to left
side operand.

Example: C = A + B will assign value of A + B into C


+=
Add AND assignment operator. It adds right operand to the left
operand and assign the result to left operand.

Example: C += A is equivalent to C = C + A

-=
Subtract AND assignment operator. It subtracts right operand from
the left operand and assign the result to left operand.

Example:C -= A is equivalent to C = C – A

*=
Multiply AND assignment operator. It multiplies right operand with
the left operand and assign the result to left operand.

Example: C *= A is equivalent to C = C * A

/=
Divide AND assignment operator. It divides left operand with the
right operand and assign the result to left operand.

Example: C /= A is equivalent to C = C / A

%=
Modulus AND assignment operator. It takes modulus using two
operands and assign the result to left operand.

Example: C %= A is equivalent to C = C % A

<<=
Left shift AND assignment operator.

Example: C <<= 2 is same as C = C << 2

>>=
Right shift AND assignment operator

Example: C >>= 2 is same as C = C >> 2

54
Java

&=
Bitwise AND assignment operator.

Example: C &= 2 is same as C = C & 2

^=
bitwise exclusive OR and assignment operator.

Example: C ^= 2 is same as C = C ^ 2

|=
bitwise inclusive OR and assignment operator.

Example: C |= 2 is same as C = C | 2

Example
The following program is a simple example that demonstrates the assignment operators.
Copy and paste the following Java program in Test.java file. Compile and run this program:

public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c);

c += a;
System.out.println("c += a = " + c);

c -= a;
System.out.println("c -= a = " + c);

c *= a;
System.out.println("c *= a = " + c);
a = 10;
c = 15;
c /= a;
System.out.println("c /= a = " + c);

a = 10;
c = 15;
c %= a;
System.out.println("c %= a = " + c);

c <<= 2;
System.out.println("c <<= 2 = " + c);

c >>= 2;
System.out.println("c >>= 2 = " + c);

c >>= 2;
System.out.println("c >>= a = " + c);

c &= a;
System.out.println("c &= 2 = " + c);

c ^= a;

System.out.println("c ^= a = " + c);

c |= a;
System.out.println("c |= a
= " + c);
}}

This will produce the following result:

c = a + b = 30
c += a = 40

56
Java

c /= a = 1
c %= a =5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
c &= a =0
c ^= a = 10
c |= a = 10

Miscellaneous Operators
There are few other operators supported by Java Language.

Conditional Operator (?)


Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide;
which value should be assigned to the variable. The operator is written as:

variable x = (expression)? value if true: value if false

Following is an example:

public class Test {

public static void main(String args[]){


int a, b;
a= 10;
b= (a == 1)? 20: 30;
System.out.println( "Value of b is : " + b );

b= (a == 10)? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This will produce the following result:

Value of b is: 30
Value of b is: 20
Instance of Operator
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type). instanceof operator is written as:

(Object reference variable) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for
the class/interface type on the right side, then the result will be true. Following is an example:

public class Test {

public static void main (String args []) {


String name = "James";
following will return true since name is type of String boolean
result = name instanceof String; System.out.println(result);
}
}

This will produce the following result:

true

This operator will still return true, if the object being compared is the assignment compatible
with the type on the right. Following is one more example:

class Vehicle {}

public class Car extends Vehicle {


public static void main (String args []){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println(result);
}
}

This will produce the following result:

true
Java

Precedence of Java Operators


Operator precedence determines the grouping of terms in an expression. This affects how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator:

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity

Postfix () [] . (dot operator) Left toright

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

= += -= *= /= %= >>= <<=
Assignment &= ^= |= Right to left
2. USING OPERATORS IN JAVA
public class{
public static void main(String []args){
java.util.Scanner scan = new java.util.Scanner(System.in);
int x,y;
System.out.println("Enter your first value: ");
x=scan.nextInt();
System.out.println("Enter your second value: ");
y=scan.nextInt();
int result=(x+y);
System.out.println("This is the result" +result);
System.out.println("Enter the operators ");
String operation=scan.next();
if(operation.equals("+")){
System.out.println("This is the addition result" +(x+y));
}else if(operation.equals("-")){
System.out.println("This is the subtraction result" +(x-y));
}else if(operation.equals("*")){
System.out.println("This is the multiplication result" +(x*y));
}else if(operation.equals("/")){
System.out.println("This is the division result" +(x/y));
}else
System.out.println("Enter the correct operation: ");
}}

2. Java Variable Example:


Add Two Numbers
1. class Simple {
2. public static void main(String [] args){
3. int a=10;
4. int b=10;
5. int c=a+b;
6. System.out.println(c);
7. }}

4. Java Variable Example:


Widening
class Simple {
public static void main (String [] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}}
4. public class Weight {
public static void main (String []args){
int age, weight, height;
age=25;
weight=50;
height=162;
System.out.println(age+weight+height);
}}
//When you give a variable name print without double quotes.
//Now if you have more than one function in your file source and you want some
variable to be used in all those functions you have to declare them.
(a) Now if you want some variable to be accessible to the whole class, not
just method but throughout your class, you have to declare before starting
your main function.

Static int age_2 = 27;


Static final int pi =3.14;
public class FirstProgram{
public static void main(String [] args){ // This is the main method

5. JAVA ARITHMETIC CLASS EXERCISE


public class Arithmetic{
public static void main(String []args){
//sum,difference and product
int i = 34;
int j = 23;
int sum = i+j;
int difference = i-j;
int product = i*j;
System.out.println(i+" "+J);
System.out.println(sum);
System.out.println(difference);
System.out.println(product);
}}
6. JAVA SCANNER MATHS
import java.util.Scanner;
public class JavaScannerMath{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the first number: ");
int num1 = input.nextInt();
System.out.println("Enter the second number: ");
int num2 = input.nextInt();
int sum = num1+num2;
System.out.println(sum);
}
}

7. MATHEMATICS OPERATION
Absolute Value
class AbsValue{
public static void main(String[]args){
double a= -33.65;
int b=185;
system.out.println("Absolute value of a: "+Math.abs(a));
system.out.println("Absolute value of b: "+Math.abs(b));
}}

You might also like