Java Operators Tutorial With Examples | Java Tutoring
Beginners Programs :

Java Operators Tutorial With Examples | Java Tutoring

Java operators, different types of operators and order of operations. The following post will mainly concern for the newbies who are new to Java field and want to learn the basics. If you have any doubts related to Java operators, do comment at the end of the post or contact us. Our Java experts might help you.

java operators with examples

What areJava Operators?

Java operators: In any programming language (and in mathematics), we use some symbols to represent an operation (calculation).

Suppose if we want to perform an addition, then we use the symbol  ” + “ Similarly when we want to perform a subtraction, then we use the symbol  ” – “ These symbols are known as mathematical operators. We have different types of operators in java. Each type (group) has some symbols (operators) in it.

Learn More On :

Different Types Of Java Operators With Examples

Based on the kind of calculation takes place with Java operators, they are divided into the following types:

  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Conditional operators
  • Assignment operators
  • Grouping operators
  • Increment/Decrement operators
  • Bitwise operators
  • Etc

A step by step guide and complete explanation of different type of java operator with detailed analysis 

1) Arithmetic Operators

  •    
  • –             
  • *            
  • /             
  • % 

Addition, subtraction, multiplication, and division are the basic mathematical operations. The java operators related to these basic operations.

We know  ” + “ is used for addition, – is used for subtraction and * is used for multiplication. These three operations will result in a single value.

For example, addition on 13 and 9 will result in 21 which is a single value. Similarly, subtraction of 9 from 13 will result in 4 which is a single value.

The same type of single value 52 will result when we multiply those two values.

But the division is a proper calculation where we get two values (quotient and remainder) as a result. Suppose if we divide 13 by 4, then 3 is the quotient, and 1 is the remainder.

Similarly, when we divide 47 by 6, then 7 is the quotient, and 5 is the remainder. In programming, we use the remainder value (after division) at many places. So there are two symbols (java operators) to get the result after division.The symbol ” / “ is used to get a quotient, and the symbol ” % “ is used to get a remainder.

These Java operators can be applied to any numeric type data as well as to char type data. But these Java operators cannot be implemented to Boolean type data.

Example # 1 : Arithmetic 

Example # 2 : Arithmetic Operators In Java

Example # 3 : Arithmetic Operators In Java

2) Relational Operators 

  •        
  • <= 
  • >= 
  • ==
  • !=

These operators compare (check relation between) two values and give a boolean value as the result. In Java, a Boolean (logical) value is either true or false (in C, these logical values are represented by 1 and 0).

Example :         

  • 13>10    is true
  • 13<10    is false
  • 13<=10 is false
  • 13>=10 is false
  • 13==10 is false
  • 13!=10  is true
  • 13<13    is false
  • 13>13    is false
  • 13==13 is true
  • 13<=13 is true
  • 13>=13 is true
  • 13!=13  is false
  • ‘A’==65 is true
  • ‘0’==48 is true
  • ‘2’==2   is false

Example #1 Program For Relational operators in Java :

3) Logical Operators 
  • &&         logical AND
  • ||            logical OR!
  • !             logical NOT

Logical Java operators also result in Boolean values. These are used to check  ” multiple Boolean values ” as a single unit. Suppose, to withdraw some amount of money from an ATM; we should have the Card, know the PIN, and we should have sufficient balance in the bank.

In this example, all the three conditions (having Card, knowing PIN, having Balance) should meet to perform Withdrawal. When writing a program for this purpose, we write a statement like :

Here we have combined ” 3 conditions “ using the &&. When we need all the conditions to be true, we combine the terms with &&.

In case if we have a situation where any one of the conditions is sufficient to be true, then we combine the conditions (expressions) using ||.

Suppose if we want to perform an operation when a user has entered ” x “in lower case or upper case, then we can write a statement like

sometimes we need to invert (reverse) the Boolean value of an expression. In that case ! can be used.

Truth table for logical java operators:

exp1      exp2      exp1 && exp2   exp1 || exp2     ! exp1   ! exp2

true       true       true                       true                       false      false

true       false      false                      true                       false      true

false      true       false                      true                       true       false

false      false      false                      false                      true       true

Example Programs # 1: Logical Java operators

3) Conditional Operator

  • ?:

We have a special operator that works based on the truth value of a condition. This java operator is known as a conditional operator. This operator contains 3 operands so it is also known as ternary operator.

To understand , first we need to discuss a known operation like ” a = 10+20; “ in this expression, result of 10+20 is assigned to  ” a “. Similarly in conditional operation, if we have an expression like a = 10==20?30:40, the result of 10==20?30:40 will be assigned to ” a “.

In this expression, 10==20 is the first operand, 30 is the second operand, and 40 is the third operand. The symbol ? is placed between first and second operands and the symbol “: “ is placed between second and third operands.

The actual result (value) of the expression is either second operand or the third operand.

This decision (second or third) is taken based on the first operand which gives true or false as a result.

If it results in true, the second operand will be the result, and if it results in false, the third operand is the result. In our example 10==20 is false, so the third operand (40) will be the result.

So the value 40 is assigned to ” a “.

Similarly, if we take an expression a = 25<40?123:456 then second operand (123) will be assigned to ‘a’ as the result of condition (first operand) is true.

Example:         

  • 16==16 ? 13 : 10                result will be 13
  • 16!=16 ? 13 : 10                 result will be 10

In this operation, both the second operand and third operand should be of the same type.

Example # 1 For Conditional:

Example # 2: Conditional Java Operator

 

4) Assignment Operators
  • =  
  • +=          
  • -=           
  • *=          
  • /=          
  • %=         
  • <<=       
  • >>=       
  • >>>=    
  • &=         
  • |=          
  • ^=

When we perform any operation, generally we assign the result of the expression to a variable. For that purpose we use a normal assignment (=).

Example:         

  • a = 10;
  • a = 10+20;
  • a = 2+3*4-5;

If we want to perform an operation on a variable and assign the result back to that variable, we can use a shortcut (combined assignment).

For example, if we want to write an expression like ” a=a+b; “ what we want is a and b should be added, and the result should be placed back in a.

Similarly we may want to perform a Java operation like length=length*3, or currentValue=currentValue+exp1*exp2; in all these cases we can use combined assignment java operators.

Example for Assignment Java Operators :         

  • a=a+b; >>> can be written as a+=b;
  • length=length*3; >> can be written as length*=3;
  •  ” currentValue=currentValue+exp1*exp2 can be written as currentValue+=exp1*exp2; “
  • n=n/10; >> can be written as n/=10;
  • val=val>>n; >> can be written as val>>=n;
  • a=a&b; >> can be written as a&=b;

Java Example Porgram For Assignment :

5) Grouping Operators

  • ( )            unit operator
  • [ ]            array operator
  • .               referencing operator (dot symbol)

 

Unit Operator( ) : :

( ) can be used to group a set of elements as a single unit. When we have an expression like  ” 2+3*4 “, as per normal priorities 3*4 is performed first and the result (12) is added to 2.

If we group 2+3 as a single unit and write the same expression like (2+3)*4, then that single unit (result 5) is multiplied with 4 and results in 20.

Example For Unit Operator :       

  • a + b / ( ( c – d ) * ( e + f ) ) % g
  • (3+4)/(5+6)
  • ( -b + Math.sqrt(b*b-4*a*c) ) / (2*a)

 

Array Operator [ ]   :

” [ ] “ are used to work with arrays.

To create a reference to an array or to access an element of an array this set of square brackets is used.

Example For Array Operator:    

  • int a[]; in creating a reference to an array
  • int a[]; in creating a reference to an array
  • a=new int[10]; in creating an array object
  • x=a[2]; in accessing an array element.

 

Dot Operator (.) : 

. (dot) operator is used to access elements/members of an object through its reference variable.

This java operators can be used to access static elements of a class using its class name.

Example for Dot Java Operator:         

  • rect1.length here we are accessing the element length of rect1
  • Thread.NORMAL_PRIORITY here we are accessing the static variable NORMAL_PRIORITY with its class named Thread

6) Bitwise Operators

  • &             bitwise AND
  • |              bitwise OR
  • ^             bitwise XOR
  • ~             bitwise NOT (negation)
  • <<           left shift
  • >>           right shift
  • >>>        unsigned right shift

Truth table

e1           e2           e1 & e2                 e1 | e2                  e1 ^ e2                 ! e2

true       true       true                       true                       false                      false

true       false      false                      true                       true                       true

false      true       false                      true                       true                       false

false      false      false                      false                      false                      true

These Java operators work on individual bits of the numbers. These java operators can be applied to integer data type only.

They cannot be applied on float, double and boolean type of data. These operators are used for masking purposes.

” & “ is used to perform bitwise AND operation on the given two values.

If we want to perform 25&78, then AND operation is performed on corresponding bits of the numbers and the result is given.

Example For AND:

  • 25 ->      00000000 00000000 00000000 00011001
  • 78 ->        00000000 00000000 00000000 01001110
  • 00000000 00000000 00000000 00001000 -> 8
  • So 25 & 78 is 8

 

Example For OR :

Similarly, 25 | 78 is

EX:         

  • 25 ->      00000000 00000000 00000000 00011001
  • 78 ->      00000000 00000000 00000000 01001110
  • 00000000 00000000 00000000 01011111 -> 95

Example For XOR :

25^78 is 87

Ex:         

  • 25 ->      00000000 00000000 00000000 00011001
  • 78 ->      00000000 00000000 00000000 01001110
  • 00000000 00000000 00000000 01010111 -> 87

Example For Bitwise Operation Left-Shift:

<< is used to shift each bit towards left to the specified number of locations. Taking an example 25, its bit pattern (taking 4 bytes) will be 00000000 00000000 00000000 00011001.

If we shift each bit 3 locations towards left, then the bits will become 00000000 00000000 00000000 11001000. When we perform a left shift for ” n “ locations, n bits at left end will be removed, and n 0s will be added at the right end.

  • 00000000 00000000 00000000 00011001 is 25
  • 00000000 00000000 00000000 11001000 is 200
  • So we can say 25<<3 is 200
  • Similarly, 6 << 9 will be 3072
  • 00000000 00000000 00000000 00000110 is 6
  • 00000000 00000000 00001100 00000000 is 3072

Instead of doing all these calculations by writing bits we can find the value by using the formula

x<<y      as            x*2y

Example:         

  • 25<<3    as            25*23       is             200
  • 6<<9      as            6*29           is             3072

Example for Right Shift:

> also behave same as << and the difference is noticeable. It (>>) shifts bits towards right for the specified number of locations.

If we shift for n positions, the rightmost n bits will be removed, and n 0s will be added to positive numbers and 1s will be added to negative numbers at the left end. Even for this we can apply a formula

Example :         

  • 25>>3     as            25/23        is             3
  • 6>>9       as            6/29          is             0
  • 500>>2   as            500/22      is             125
  • -500>>2  as          -500/22      is             -125
  • -15>>1    as            -15/21      is             -8 (yes, it is -8 but not -7)
  • -5>>1      as            -5/21        is             -3
  • 5>>1        as            5/21        is             2 (yes, 5 is positive, so result is 2)

>>> is similar to >> but only 0s are added at the left end for both positive and negative numbers.

7) Increment and Decrement Operators

  • ++          

These are used to increment/decrement a value by 1. Generally to increment a value in the variable x by 1 we use the statement like x=x+1;

The same statement can be written like x+=1; also using combined assignment operator. Alternatively, we can use x++ or ++x to perform the same thing. Similarly, x=x-1; can be written as –x or x– also.

These java operators should be applied on variables only. They cannot be applied on constants.

Example:         

  • a++            is valid
  • 5++             is not valid
  • a++++          is not valid
  • a++ + a++     is valid

Generally, all other unary java operators are used in prefix notation only. But these unary java operators can be used in prefix as well as postfix notations.

Example:         

  • +a           ~a           -a            !a             are valid
  • a+           a~           a-            a!             are not valid
  • a++        ++a        a–          –a              are valid

   There is a small difference between working of prefix and postfix notations.

When ++ is used in prefix notation; the increment will take place first on the variable and then the resulting value will be utilized in the expression.

Eg1:        int a=5;

int b=++a; here ”  a “ is incremented first (so that it becomes 6) and then that 6 is assigned to b.

Eg2:        int x=5;

Int y=++x + ++x; here, with the first ++x, a incremented to 6 and the 6 is used in place of that ++x. With the second ++x, x is incremented to 7 and that 7 is used in place of that.

So by the time both the ++ operations are completed the expression will become y= 6+7; so y becomes 13.

When ++ is used in the postfix notation, the original value (before increment) is utilized in the expression first then increment will take place.

Eg1:        int a=5;

Int b=a++; here the original value of a (5) is used as a value of the expression a++, and then a is incremented.

So the value 5 is assigned to b and value of a will be 6.

Eg2:        int x=5;

Int y=x++ + x++; here, with the first x++, value of the expression becomes 5 and x is incremented to 6. With the second x++, the value of an expression will be 6 (by that time x is 6) and x is incremented to 7.

So the expression will become y=5+6; so 11 is assigned to y.

Example # 1: 

Example # 2:

Example # 3 :

Based on the number of operands associated with an operator, Are divided into 3 types

  1. Unary operators
  2. Binary ——–
  3. Ternary  ——–

Work on single operand are known as unary.

Eg:          ++a        –a          +a           -a            ~a           !a            etc

work on two operands is known as binary.

Eg:          a+b        a-b         a*b        a&b        a^b        a<<b      a=b        a==b      a<=b      a&&b    etc

If you have any doubts related to this section, do comment at the end of the post. One of our java expert authors will be in touch with you 🙂

About The Author

Path Thomas works as a senior Java programmer analyst at IBM. He had a high command on Java and always updated with the latest versions. He also teaches the students who are new to Java course.