All About Operators in Java



An operator takes one or more arguments and produces a new value. The arguments are in little different from ordinary method calls but results the same. All operators produces a value from their operand. An operator can change the value of an operand. This is called a side effect.The most common use for operators that modify their operand is to generate the side effect.But the value produced is available for our use as in operators without side effect.

There are the below types of operators available in java

  1. Arithmetic operator
  2. Concatenation operator
  3. Assignment operator
  4. Unary operator
  5. Relational operator
  6. Ternary operator
  7. Conditional operator
  8. Type comparison operator
  9. Bitwise operator
  10. Shift operator
  11. Other Operator


Arithmetic Operator
Mixed Mode Arithmetic
when one of the operands is real and other in other type,the expression is called a mixed mode arithmetic expression.Compiler will check for higher type of the operands and converts the lower type to higher type and carry out the operation.

=20/10 //will produce 2 and 
=20/10.0 // will produce 2.0
 


Operator Expression Example Comment
Addition + a+b For numerical values it is addition
Substraction - a-b Subtracts right from left
Multiplication * a*b multiplies left with right
Divition / a/b
Modulas % a%b applicable for integer data
Concatenation operator:
only operator that supports operator overloading in java. In normal context '+' works as addition but in String context,it works as a concatenate.If an expression begins with a String,then all operands that follow must be String.

public class MyStringTest{
     public static void main(String []args){
        int i=1;
        int j=2;
        int k=3;
        String myString="i j k ";
        System.out.println(myString+i+j+k);
        System.out.println(i+j+k+myString);
     }
}
 
Output of the code:
$javac MyStringTest.java
$java -Xmx128M -Xms16M MyStringTest
i j k 123
6 i j k

As the expression begins with String compiler will convert i,j,k into String and concatenate instead of addition.
Operator Expression Example Comment
Concatenation + "Java"+" "+"Love" String context it is concatenation
Assignment operator
They are mainly classified as:

  • Direct assignment
  • Shorthand assignment


Operator Expression Example Comment
assignment = c=a+b assigns the result to the left
subtract AND -= a-=b it is equivalent to a=a-b
add AND += a+=b it is equivalent to a=a+b
divide AND /= a/=b it is equivalent to a=a/b
multiply AND *= a*=b it is equivalent to a=a*b
No space between op and =will be allowed and generic syntax is identifier op=expression.It is also called short hand operator, as it follows short hand notations.
Advantages:

  1. What appears on the left hand side need not be repeated and therefore it becomes easier to write.
  2. The statement is more concise and easier to read.
  3. This results a more efficient code.


Unary operator
The unary plus and minus operator are same as binary plus and minus.The unary minus produces the negative of the value.Unary plus provides symmetry with unary plus

x=-a;
x=a*-b;
x=a*(-b);
 
Operator Expression Example Comment
unary plus + Indicates positive values
unary minus - negates an expression
increment ++ a++ Increments the value by one
decrement -- a-- decrement the value by one
++ and -- is also called Auto increment and Auto decrements operators. They have two flavors of it.
  • pre increment and post increment
  • pre decrement and post decrement

int i=1;
++i;//(i=2) pre increment and then assignment
i++;(i=2 first assignment and then increment)
//final value i=1
//similarly
--i;(i=2 predecrement and assignment)
i--;(i=2 assignment and then decrement)
//final value i=1
 


Relational operator
Relational operator generates a boolean result.They evaluate the relationship between the values of the operands.A relational expression produces true if the relationship is true and false otherwise.Equivalence and non equivalence works well with all build in data types but other comparisons won't work with type boolean.
Operator Expression Example Comment
not ! !a logical compliment operator inverts the value of a returns boolean
equals == a==b checks equality, returns boolean
not equal to != a!=b checks if a is not equal to b, returns boolean
greater than > a>b checks if a is greater than b, returns boolean
less than < a<b checks if a is less than b returns boolean
greater than equal to >= a>=b checks if a is greater than or equals to b, returns boolean
less than equal to <= a<=b checks if a is less than or equals to b, returns boolean
These operators can be applied to any type of data and only returns true or false.when arithmetic expressions are used on either side of a rational operator,the arithmetic expression will be evaluated first then the result is compared. Thus Arithmetic operators will have higher priority over rational operators.

a+b==c+d //is true if both side are equal.
 
Relatational operators are used in decision statements such as if,while etc to decide the next course of action.
Conditional operator or Logical Operator:
They are also called logical operators.It produces a boolean result as true or false based on the logical relationship of its arguments.They can be used in the boolean context not for other data types.They are used when we want to form a compound conditions by combining two or more relations.
Operator Expression Example Comment
conditional AND   &&   a&&b
conditional OR || a||b
Short circuiting:
Short circuiting means that the expression will be evaluated until the truth or falsehood of the entire expression can be unambiguously determined.As a result all the parts of a logical expression may not get evaluated.Like-

if(test1()&&test2()&&test3())
 
In this example if test1() function returns true,control will try to execute test2() function,if test2() returns true then test3() will be executed. Now if any of these function generate a false output,the whole expression becomes false,irrespective of the yield of the other functions.Java will not carry out the execution of the other function if it detects any false statement or false yield from any of the functions while going from left to right.This leads to potential performance increase if all the parts of the logical expression do not need to be executed.
They follow the below truth table:
Operator -1 Operator-2 Operator1&&operator2 Operator1||operator2
true true true true
true false false true
false true false true
false false false false

Ternary operator
it is known as arithmetic if operator having symbol ?:.This operator is unusual because of only three operands.Since it produces a value it is truly an operator.
the generic syntax:

x=(expession1)?(expession2):expession3
//it is equivalent to
if(expession1){
x=expession2;
}
else{
x=expession3;
}
 
The logic is if expession1 is evaluated and it is true then the expession2 is evaluated and the operator produces expession2 value .If it is false the then expession3 is evaluated and the operator produces expession3 value.It is very much distinct from if else .It is more compact as well.But it is less easier to understand.:(

public class MyTernaryTest{

     public static void main(String []args){
        for(int i=1;i<100;i=i+10)
        {
            System.out.println("The value of i "+i+" "+myTernary(i));
        }
     }
     private static int myTernary(int i)
     {
         return i<10?i*100:i*10;
     }
}


The output of the code:
$javac MyTernaryTest.java
$java -Xmx128M -Xms16M MyTernaryTest
The value of i 1 100
The value of i 11 110
The value of i 21 210
The value of i 31 310
The value of i 41 410
The value of i 51 510
The value of i 61 610
The value of i 71 710
The value of i 81 810
The value of i 91 910
Type comparison operator
instanceOf compares an object to a specified type.It returns boolean value.The instanceOf is an object reference operator and returns true if the object on the left hand side is an instance of the class given in the right hand side.

if(student instanceOf Student)
{
}
else
{
}
//or Triangle instanceOf Shape
 
they return true if student is an instance of Student or Triangle is an instance of Shape.
Bitwise operator
Bitwise operator allows us to manipulate bits in an integral primitive data type. Bitwise operators perform boolean algebra on the corresponding bits in the two arguments to produce a result.The Bitwise operators are often manipulate hardware directly and have to set the bits in hardware registers.Java was originally designed to be embedded in TV settop boxes and so this lowlevel orientation still make sense!!.
Bitwise AND operator(&) produces a one in the output bit if both input bits are one,otherwise it produces zero.
Bitwise OR operator(|) produces a one in the output bit one of the input bits is one,it produces zero if both are zero.
Bitwise Exclusive OR or XOR operator(|) produces a one in the output if one or the other input bit is one,but not both.
Bitwise NOT(~) or complement operator is unary operator. It only takes one argument(all other bitwise operator are binary operator).It produces the opposite of the input bit.A one if the input bit is zero and a zero if the input bit is one.
Bitwise operators and logical operators uses same character as bits are small. There is only one character in the bitwise operator.
Bitwise operators can be combined with =,&=,|=,^=. ~ is an unary operator and can not be combined with = sign.
The boolean type is treated as an one bit value so it is somewhat different.We can perform a bitwise AND,OR,XOR but can not perform NOT.

Shift operator
The shift operators also manipulate bits.They can only be used on primitive integral types.The left shift operator(<<) produces the operand to the left of the operator shifted to the left by the number of bits specified after the operator.(By inserting zeros at the lower order bits).

The signed right shift operator(>>) produces the operand to the left of the operator shifted to right by the number of bits specified after the operator.The signed right shift (>>) uses sign extension.If the value is positive,zeros are inserted at the higher order bits.If the value is negative,ones are inserted at the higher order bits.

Java also has added unsigned right shift(>>>) which uses zero extension,regardless of the sign,zeros are inserted at the higher order bits.If we shift a char,byte or short, it will be promoted to int before the shift operation takes place.The result will be in int.Only  the five order bits of the right hand side will be used.This prevents shifting more than the number of bits in an int.If we are operating on long,long will be the result.Only six low order bits of the right hand side will be used.This prevents us from shifting more than the number of bits in an int.
Shifts can be combined with equal sign like-<<=,>= or >>>=.The value is replaced by the lvalue shifted by rvalue.

static void bitInt(String s,int i)
{
System.out.println(s+",int:"+i+",binary:");
System.out.println(" ");
for(int j=31;j>=0;j--)
if(((1<<j)&j>!=0)
System.out.println("1");
else
System.out.println("0");
}

Operator Expression Example Comment
left shift << <<a
right shift >> a>>
signed right shift >>> a>>>
Other operators:
  • a dot (.) operator is used to access member elements of an object.like student.getName().It is also used to access the classes and sub package from a package
  • a parenthesis () operator determines the precedence of operator inside them
  • a square [] operator is used for array indexing.
  • a comma operator is used as a separator in function argument lists,it is also used in for loop for sequential evaluation. 
If we try to use arithmetic operators on boolean data type,compiler will throw a compilation error.The operator-operator name is undefined for the argument type boolean.

boolean a=true;
boolean b=false
a=a+b;// compile time error
 
All About Operators in Java All About Operators in Java Reviewed by Animesh Chatterjee on October 24, 2018 Rating: 5

No comments:

Powered by Blogger.