Operators in Java

In my previous article i explained, how to declare and initialize variables. In this article, i will explain how to perform different operations on them. Java operators are special symbols used to perform specific operations on one, two or three operands and returns the result.

Operator Precedence

Operator Precedence

Above table explores the precedence of operators, which operators have the highest precedence. In above table operators are listed in precedence order. The top most operator have the highest precedence then the lower one. Operators with highest precedence are evaluated first then the operators of the lower precedence. Operators from the same row have equal precedence, when operators of same precedence appears in one statement then a rule must handle it that which one is evaluated first. All binary operators except assignment operator are evaluated from left to right where as assignment operators are evaluated from right to left.
Assignment Operators : One of the most common operators used in java is assignment “=” operator. In java, assignment operator is also used to assign object reference to another object.

int id=10; String name= "Azam"; 

Arithmetic Operators : Java provides arithmetic operators to perform addition, multiplication, subtraction and division. Only the operator you might not be familiar is “%” used to compute reminder of two operands by dividing one operand with another one.

+ additive operator and can be used for concatenation purpose
- subtraction operator
* multiplication operator
/ division operator
% remainder operator
public class ArithmeticOperators {
public static void main(String[] args) {
int result = 2 + 2; // result is now 4
System.out.println(result);
result = result - 2; // result is now 2
System.out.println(result);
result = result * 3; // result is now 6
System.out.println(result);
result = result / 3; // result is now 2
System.out.println(result);
result = result + 8; // result is now 10
result = result % 7; // result is now 3
System.out.println(result);
String str1 ="Welcome to "; // String one
String str2 = "Java"; //String two
String concat = str1+str2; // Concatenating string one and string two
System.out.println("Concatenated string is "+ concat);
}
}

Unary Operators :The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

+     Unary plus operator; indicates positive value
      (numbers are positive without this, however)
-     Unary minus operator; negates an expression
++    Increment operator; increments a value by 1
--    Decrement operator; decrements a value by 1
!     Logical complement operator; inverts the value of a boolean
 class UnaryOperators {
public static void main(String[] args){
int result = +1; // result is now 1
System.out.println(result);
result--; // result is now 0
System.out.println(result);
result++; // result is now 1
System.out.println(result);
result = -result; // result is now -1
System.out.println(result);
boolean success = false;
System.out.println(success); // false
System.out.println(!success); // true
}
}

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn’t really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

int result=1;
result++; System.out.println(result); //result is 2
++result; System.out.println(result); //result is 3
result--; System.out.println(result); //result is 2
--result; System.out.println(result); //result is 1

Equality and Relational Operators : 

The equality and relational operators determine if one operator is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use “==”, not “=”, when testing if two primitive values are equal.

==   equal to
!=   not equal to
>    greater than
>=   greater than or equal to
<    less than
<=   less than or equal to
class ComparisonOperator {
public static void main(String[] args) {
int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2");
if(value1 != value2)
System.out.println("value1 != value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2)
System.out.println("value1 <= value2");
}
}
Output:
value1 != value2
value1 < value2
value1 <= value2

Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit “short-circuiting” behavior, which means that the second operand is evaluated only if needed.

&&   Conditional-AND
||   Conditional-OR
 int val1 =1; int val2= 2;
boolean condition = (val1==1) && (val2==2);
System.out.println(condition);

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement. This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: “If someCondition is TRue, assign the true to condtion. Otherwise, assign the false to condition.”

int val1 =1; int val2= 1;
boolean condition = (val1==val2) ? true : false;
System.out.println(condition); 

Comparison Operator instanceOf
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The following program, defines a parent class (named A), a simple interface (named X), and a child class (named B) that inherits from the parent and implements the interface.

interface X {
void print();
}

class A {}

class B extends A implements X {
public void print() { }
}

public class Test {
public static void main(String[] args) {
B b = new B();
if (b instanceof X)
System.out.println("b is an instance of X");
if (b instanceof A)
System.out.println("b is an instance of A");
}
}
Output:
b is an instance of X
b is an instance of A

Comments

  1. By Danial

    Reply

  2. By Raj

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.