Java Operators

Back to home Java Operators
Logicmojo - Updated Jan 1, 2024



Introduction

The formula that is capable of performing an operation using one or more of the operands is said to have an operator. Let's use the formula 15 + 9 = 24 as an example. Here, the operands are 15 and 9, and the operator is denoted by " + ". In some circumstances, we can utilize operators for both one and more than two operands. We'll be discussing about Java operators in this section.

In-depth explanations of operators and their types are provided in this article, along with examples of how to use them.


What Is Java Operators ?

An operator is a symbol that instructs the compiler to do a specific operation. Java includes a large number of operators for dealing with various types of operations. When doing arithmetic operations, we utilize the plus (+) operator for addition, multiply(*) for multiplication, and so on.

In Java, an operator is a symbol that is used to execute operations. Operators are constructs that can change the values of operands.

Different Types Of Java Operators

Java Operators

The types below informs us about the whole different types of operators offered by the Java programming language.

  1. Unary Operators

  2. Arithmetic Operators

  3. Relational Operators

  4. Logical Operators

  5. Bitwise Operators

  6. Assignment Operators

  7. Shift Operators

  8. Ternary Operators





Learn More

Unary Operatos

In Java, unary operators require a single operand. They are used for increment and decrement values as well as to negotiate a value. Unary operators can also be used to reverse a Boolean value. The table below depicts various unary operators and what they perform.



Operator Operator Name Function
+ Unary Plus The unary plus operator translates byte, character, and short datatype values to integer values. However, it is unnecessary because an explicit translation of character to integer may additionally be performed.
Unary Minus Changes a positive value consciously into a negative value.
++ Increment By using this operator, the value is increased by 1. Post-increment (x++) and pre-increment (++x) are the two types of increment.
-- Decrement By using this operator, the value is reduced by 1. There are two types of decrement: post-decrement (x--) and pre-decrement (--x).
! Logical not Operator A boolean value can be inverted using this operator (!x).



Program to Understand Unary Operators in Java:

public class Main {
public static void main ( String[] args ) {  
int x = 5;  
boolean y = true;
// post-increment operator
System.out.println ( x++ );
// pre-increment operator
System.out.println ( ++x );
// post-decrement operator
System.out.println ( x-- );  
// pre-decrement operator
System.out.println ( --x );

System.out.println ( !y );
}
}

Output

5
7
7
5
false

The ++ and -- operators are used as prefixes in the program mentioned above (++x, --y). These operators (x++, y++) can be used as postfix as well.

When these operators are used as prefixes vs postfixes, there is a small variation.

Arthematic Operatos

In Java, multiplicative and additive operations such as addition, subtraction, multiplication, division, and modulus are performed via arithmetic operators. The table below describes various arithmetic operators and what they perform.



Operator Operator Name Function
+ Addition To add the value of the operands
Subtraction To subtract the right-hand operator with the left hand operator
* Multiplication To multiply the value of the operands
/ Division To divide the left hand operator with right hand operator
% Modulus To divide the left hand operator with right hand operator and returns remainder



Note- The answer is a floating point number when an integer and a floating point number are utilized as operands in a single arithmetic operation.
The % operator is most often used with integers.


Program to Understand Arithmetic Operators in Java:

public class Main
{
    public static void main (String[]args)
    {
        int x = 5;
        int y = 10;
        // addition operator
        System.out.println (x + y);
        
        // substraction operator
        System.out.println (x - y);
        
        // multiplication operator
        System.out.println (x * y);
        
        // division operator
        System.out.println (x / y);
        
        // modulus operator
        System.out.println (x % y);
    }
}

Output

15
-5
50
0
5

Relational Operatos

Java uses relational operators to examine relationships between two operands.Decision-making and looping both require relational operators. Different relational operators are included in the table below along with what they perform.



Operator Operator Name Function
== Equal to determines whether the values of two operands are equal, and if they are, the condition is satisfied.
!= Not Equal to determines if the values of two operands are equal or not; if they are not, the condition is false.
< Less than determines whether the left operand's value is lower than the right operand's value; if so, the condition is satisfied.
> Greater than determines whether the left operand's value is higher than the right operand's value; if so, the condition is satisfied.
<= Less than or equal to determines whether the left operand's value is lower than or equal to the right operand's value; if so, the condition is satisfied.
>= Greater than or equal to determines whether the left operand's value is higher than or equal to the right operand's value; if so, the condition is satisfied.



Program to Understand Relational Operators in Java:

public class Main 
{
    public static void main ( String[] args ) 
    {
        int  x = 5;
        int  y = 10;
        
        System.out.println ( x < y );   // Greater than operator
        System.out.println(  x > y );   // Less than operator
        System.out.println ( x <= y );  // Less than or equal to operator
        System.out.println (x >= y );   // Greater than or equal to operator
        System.out.println ( x == y );  // Not Equal to operator
        System.out.println ( x != y );  // Equal to operator
    }
}

Output

true
false
true
false
false
true

Logical Operatos

Java uses logical operators to execute out logical AND, OR, and NOT operations. The functions of the various logical operators are listed in the table below.



Operator Operator Name Function
&& Logical AND It returns True if both the operands are true, otherwise, it returns False.
|| Logical OR It returns True if either the operands are true, otherwise it returns False.
! Logical NOT It returns True if an operand is False. It reverses the logical state of an operand.



Program to Understand Logical Operators in Java:

public class Main 
{
    public static void main ( String[] args ) 
    {
    
    System.out.println((10 > 5) && (15 > 10));  // Logical NOT operator
    System.out.println((10 > 5) && (15 < 10));  
    
    System.out.println((10 < 5) || (15 > 10));  // Logical OR operator
    System.out.println((10 < 5) || (15 < 10));  

    
    System.out.println(!(10 == 5));             // Logical NOT operator
    System.out.println(!(10 > 5));  
  }
}

How Relational Operator Work

  1. (10 > 5) && (15 > 10) returns true as both (10 > 5) and (15 > 10) are true.

  2. (10 > 5) && (15 < 10) returns false as the expression (15 < 10) is false.

  3. (10 < 5) || (15 > 10) returns true as the expression (15 > 10) is true.as

  4. (10 < 5) || (15 < 10) returns false as both (10 < 5) and (15 < 10) are false.

  5. !(10 == 5) returns true as 10 == 5 is false.

  6. !(10 > 5) returns false as 10 > 5 is true.

Output

true
false
true
false
true
false

If and only if both of the Expressions are true, we know that the outcome of the logical AND operator on two Expressions evaluates to true. Therefore, there is no need to evaluate the second Expression if any of the Expression evaluate false.

Exp1 && Exp2

The second Expressions Exp2 is not examined if the first Expression Exp1 evaluates to false.

Bitwise Operatos

Bitwise Operators are operators that work instantly on bits. On our computers, numbers are often represented as bits: a series of zeros and ones. They are utilized when operations on individual bits are required. It works with any integer type.



Operator Operator Name Function
& Bitwise AND It takes two numbers as operands and does AND on every bit of two numbers.
| Bitwise OR It takes two numbers as operands and does OR on every bit of two numbers.
^ Bitwise XOR It takes two numbers as operands and does XOR on every bit of two numbers.
~ Bitwise NOT It takes one number as an operand and does invert all bits of that number.



Example

Assume x = 45 and y = 22 in binary form, as shown below.

x = 0010 1101

y = 0001 0110

Lets see how Bitwise works,

x&y = 0000 0100

y

x|y = 0011 1111

x^y = 0011 1011

~x = 0011 0001



Program to Understand Bitwise Operators in Java:

public class Main 
{
    public static void main( String[] args ) 
    {
        int x = 45; 
        int y = 22; 
        
        System.out.println ( x&y );  // Bitwise AND operator
       	System.out.println ( x|y );  // Bitwise OR operator
        System.out.println ( x^y );  // Bitwise XOR operator
        System.out.println ( ~x );   // Bitwise Not operator
	}
}

Output

4
63
59
-46

Assignment Operatos

The assignment operator is used to change the value of a variable. The assignment operator's left side operand is known as variable, and the assignment operator's right side operand is known as value.



Operator Operator Name Function
= Simple assignment It is used to assign the value on the right to the operand on the left
+= Add AND assignment It is used to add right operand to the left operand and assigns the result to the left operand.
-= Subtract AND assignment It subtracts right operand from the left operand and assigns the result to the left operand.
*= Multiply AND assignment It multiplies right operand with the left operand and assigns the result to the left operand.
/= Divide AND assignment It divides left operand with the right operand and assigns the result to the left operand.
%= Modulus AND assignment It is used to divide the left-hand operator with right hand operator and assigns the result to left operand.
^= Bitwise exclusive OR and assignment It performs exponential calculation on operators and assigns value to the left operand



Program to Understand Assignment Operators in Java:

public class Main 
{
    public static void main ( String[] args ) 
    {
        int x = 5;
        int y = 10;
        int z;
        
        System.out.println ( z = x + y );   //Simple assignment
        System.out.println ( y += x );      //Add AND assignment
        System.out.println ( y -= x);       //Subtract AND assignment
        System.out.println ( y *= x );      //Multiply AND assignment
        System.out.println ( y /= x );      //Divide AND assignment
        System.out.println ( y %= x );      //Modulus AND assignment
        System.out.println ( y ^= x );      //Bitwise exclusive OR and assignment
    }
}

Output

15
15
10
50
10
0
5

Shift Operatos

The assignment operator is used to change the value of a variable. The assignment operator's left side operand is known as variable, and the assignment operator's right side operand is known as value.



Operator Operator Name Function
<< Left Shift It shifts the bits of the number two places to the left and fills the voids with 0’s.
>> Right Shift It shifts the bits of the number two places to the right and fills the voids with 0’s The sign of the number decides the value of the left bit.
>>> Unsigned Right Shift It 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.



Program to Understand Shift Operators in Java:

public class Main
{
    public static void main (String[]args)
    {
        int a = 10;
        System.out.println (a << 2);  //left shift
        System.out.println (a >> 2);  //right shift
    } 
}

Output

40
2

Ternary Operatos

The ternary operator in Java reduces and mimics the if else expression. It's made up of a condition and a question mark (?). It has two expressions that are separated by a colon (:). If the condition is true, the first expression is executed; otherwise, the second expression is executed.

Syntax

variable x = (condition) ? Exp1 (if condition is true) : Exp2( if condition is false)

The value returned by either expression is stored in variable.


Program to Understand Ternary Operators in Java:

public class Main 
{  
    public static void main ( String args[] ) 
    {  
        int x = 10;  
        int y = 5;  
        int greater = ( x > y ) ? x : y;  
        System.out.println ( "The greater value is : " + greater );  
    }
}  

Output

The greater value is : 10

Misc Operatos

instanceof Operator

It's solely used for object reference variables. It determines whether or not the object is of the interface or class type.

Syntax

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

The value returned by either expression is stored in variable.


Program to Understand Ternary Operators in Java:

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

      String name = "Logicmojo";

      // if string name will be same, it will return true
      boolean practice = name instanceof String;
      System.out.println( "The condition is " + practice );
   }
} 

Output

The condition is true   

Precedence & Association of Java Operators

When an expression contains several operators, Java offers well-defined rules for establishing the order in which the operators in the expression are evaluated. Multiplication and division, for example, take precedence over addition and subtraction. Explicit parentheses can override precedence rules. When addressing composite problems containing a maximum of one type of operator, precedence and associative principles are applied. As there might be many possible valuations for the same equation, these principles determine which component of the equation to analyze first.


Precedence of Operators

If there are many operators with different precedence, operator precedence decides which operator is performed first in an expression.

For example, x + y * z is calculated as x + (y * z), whereas x * y + z is calculated as (x * y) + z , because multiplication takes precedence over addition,


Associativity of Operators

When two operators in an expression have the same precedence, operator associativity is utilized.

For example, the compiler will evaluate an expression such as x=y=z=1 as (x=(y=(z=1))).

The terms are linked together through association. Some operators, however, do not have an order of relationship. These are referred to as non-associative operators. Associativity is classified into two types: left to right and right to left.



Category OperatorAssociativity
Postfix++ , -- Left to right
Unary + - ! ~ ++ -- Right to left
Multiplicative * / %Left to right
Additive + - Left to right
Shift << >>, >>> Left to right
Relational < <= > >= instanceof 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
Comma , Left to right



Advantages and Disadvantages of Operators in Java

Advantages of Operators in Java:

  1. Simplified Expression: Operators allow developers to perform complex computations and operations using simple and concise expressions. This simplifies the code and makes it more readable.

  2. Efficient Data Manipulation: Operators provide efficient ways to manipulate data, such as performing arithmetic calculations, logical operations, and bit manipulations. This leads to optimized code execution.

  3. Enhanced Productivity: Java operators enable developers to write code more efficiently, reducing the number of lines required for a task. As a result, it increases overall productivity during the development process.

  4. Flexibility in Logic Building: Java operators offer various logical and conditional operators, which allow developers to create flexible and sophisticated decision-making structures within their programs.

  5. Increment and Decrement Operations: The increment (++) and decrement (--) operators are particularly useful for loops and control structures. They simplify the process of updating variables in iterations.

  6. Comparisons and Conditions: Relational operators (e.g., <, >, ==, !=) enable easy comparisons between variables, which are essential for decision-making and branching in Java programs.

  7. Bitwise Manipulation: Bitwise operators (e.g., &, |, ^) facilitate low-level bit manipulation, which is valuable for tasks such as working with flags, setting/clearing specific bits, and other bitwise operations.


Disadvantages of Operators in Java:

  1. Potential for Error: Misusing operators or using incorrect operands can lead to logical errors or unexpected behavior in the program. Developers need to be cautious when working with operators to avoid unintended consequences.

  2. Code Complexity: While operators can simplify expressions, complex expressions that involve multiple operators may lead to code that is hard to understand and maintain. It's essential to strike a balance between simplicity and complexity.

  3. Division by Zero: Division operators (/ and %) can lead to runtime errors if the denominator is zero. Developers must handle such cases by adding appropriate checks to avoid exceptions.

  4. Bitwise Confusion: Bitwise operators can be tricky to understand for those not familiar with low-level bit manipulation. Using these operators without a clear understanding may lead to unintended results.

  5. Type Conversion Issues: Certain operators may perform implicit type conversions, which can lead to data loss or unexpected results. Developers need to be aware of type casting rules to avoid such issues.




Conclusions

We covered the different types of Java Operators in this article. The operators are a significant component of Java and are required to conduct various data operations. In Java, there are many different sorts of operators, each with its own specialized purpose. While some operators are more commonly used than others, they can all be beneficial in the correct situation. Anyone can learn to use Java operators with a little effort.

Good luck and happy learning!








Frequently Asked Questions (FAQs)


Operators are special symbols in Java used to perform various operations on data. They enable manipulation, comparison, and logical evaluations. For example, the addition operator (+) performs addition, and the expression 5+4 returns the value 9.

There are several types of operators in Java:

  • Arithmetic Operators: Perform basic mathematical operations like addition, subtraction, multiplication, division, and more.
  • Relational Operators: Compare values and return boolean results like true or false.
  • Logical Operators: Combine conditions and evaluate the result as true or false.
  • Bitwise Operators: Perform operations at the bit level, useful in low-level programming.
  • Assignment Operators: Assign values to variables, often used in variable updates.
  • Conditional Operator: Also known as the ternary operator, it provides a shorthand for if-else statements.
  • Instanceof Operator: Checks if an object is an instance of a specific class or its subclasses.
  • Type Cast Operator: Explicitly converts one data type to another.

Understanding and utilizing Java operators effectively is essential for writing efficient and expressive code.


In Java, the '>>>' operator is the unsigned right shift operator. It is used to shift the bits of a binary number to the right by a specified number of positions. The unique characteristic of the unsigned right shift operator is that it always fills the vacant positions with 0, regardless of the sign of the number being shifted.

Unlike the regular right shift operator '>>', which fills the vacant positions with the sign bit (0 for positive numbers and 1 for negative numbers), the '>>>' operator ensures that the result is treated as a non-negative value.

This operator is particularly useful when dealing with binary representations of positive numbers or unsigned data types, where the sign bit does not play a role in the intended calculation. It allows for efficient and accurate bit manipulation without affecting the final result's correctness.


In Java, there are eight main types of operators that are used to perform various operations on data:

  1. Unary Operators: These operators work on a single operand and include the increment (++) and decrement (--) operators, among others.
  2. Arithmetic Operators: These operators perform basic mathematical operations like addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
  3. Assignment Operators: These operators are used to assign values to variables, such as the assignment operator (=) and compound assignment operators (+=, -=, etc.).
  4. Logical Operators: These operators are used for combining multiple conditions and include logical AND (&&), logical OR (||), and logical NOT (!).
  5. Shift Operators: These operators perform bit-level shifting of binary numbers and include the left shift (<<) and right shift (>>) operators.
  6. Bitwise Operators: These operators work on individual bits of data and include bitwise AND (&), bitwise OR (|), bitwise XOR (^), and bitwise NOT (~).
  7. Ternary Operators: Also known as the conditional operator, it provides a shorthand for if-else statements with the syntax "condition ? expression1 : expression2".
  8. Relational Operators: These operators compare two values and return boolean results, such as equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).

Operators in programming languages like Java are used to perform various tasks and operations on data. They enable developers to manipulate, compare, and evaluate values effectively.

Arithmetic Operators: These operators are utilized to perform basic mathematical calculations, such as addition, subtraction, multiplication, division, and modulus. For example, they can be used to calculate the sum of two numbers or find the remainder of a division.

Assignment Operators: Assignment operators are used to assign values to variables or properties. They can be used to update numeric, date, system, time, or text values. For instance, they can set a variable to a specific number or assign a date to a date property.

Comparison Operators: Comparison operators are employed to compare values and return boolean results (true or false) based on the comparison. They are useful for decision-making and conditional branching. For example, they can determine if one value is equal to, greater than, or less than another value.


Percent Sign (%)

In Java, the percent sign (%) is used to represent the modulus operator. The modulus operator is a mathematical operator that works specifically on integers and returns the remainder when one number is divided by another.

For example, if we have two integers, 'a' and 'b', then the expression 'a % b' will give us the remainder when 'a' is divided by 'b'.

The modulus operator is particularly useful in various programming scenarios. It is commonly employed to check whether a number is even or odd, as the remainder of an even number divided by 2 will be 0, while for odd numbers it will be 1.

Additionally, the modulus operator is utilized in applications like finding multiples, determining cyclic patterns, and manipulating array indices.

In Java, the percent sign (%) serves as a quick way to access the result of the modulus operation and provides a handy tool for performing various calculations involving remainders and cyclic behaviors in programming.


In Java, there are five main arithmetic operators that are used to perform basic mathematical calculations:

  1. Addition (+): The addition operator is represented by the plus sign (+). It is used to add two operands together, either numeric values or strings. For example, 5 + 3 will yield 8, and "Hello, " + "World" will result in "Hello, World".
  2. Subtraction (-): The subtraction operator is represented by the minus sign (-). It subtracts the second operand from the first. For instance, 7 - 2 will return 5.
  3. Multiplication (*): The multiplication operator is represented by the asterisk (*). It multiplies two operands to obtain the product. For example, 4 * 6 will give 24.
  4. Division (/): The division operator is represented by the forward slash (/). It divides the first operand by the second to obtain the quotient. Be cautious with integer division, as it may truncate the result. For example, 10 / 3 will yield 3.
  5. Modulus (%): The modulus operator is represented by the percent sign (%). It calculates the remainder when the first operand is divided by the second. For example, 10 % 3 will give 1, as the remainder of 10 divided by 3 is 1.

Arithmetic operators are fundamental in programming and are used extensively in various mathematical and algorithmic computations, making them essential for writing efficient and expressive Java code.


A logical operator in Java is a symbol or word that connects two or more expressions to create a compound expression. The value of this compound expression depends solely on the original expressions and the meaning of the operator. Logical operators are essential for making decisions and performing conditional operations in programming.

There are three common logical operators in Java:

  • AND (&&): The logical AND operator returns true if both of the connected expressions are true. Otherwise, it evaluates to false. For example, if (x > 5 && y < 10) will be true only if 'x' is greater than 5 and 'y' is less than 10.
  • OR (||): The logical OR operator returns true if at least one of the connected expressions is true. If both expressions are false, it evaluates to false. For example, if (x == 0 || y == 0) will be true if either 'x' or 'y' is equal to 0.
  • NOT (!): The logical NOT operator is used to negate the value of a single expression. It returns true if the expression is false and false if the expression is true. For example, if !(x > 10) will be true if 'x' is not greater than 10.

Logical operators are fundamental for creating complex conditions, making decisions based on multiple criteria, and controlling the flow of execution in Java programs.


In Java, symbols refer to the various characters and punctuation marks used as identifiers, operators, delimiters, and syntax elements in the programming language. Symbols play a crucial role in representing and interpreting code.

Here are the main points regarding symbols in Java:

  • Identifiers: Symbols are used as identifiers to name variables, methods, classes, and other program elements. Identifiers must follow specific naming rules and conventions, such as starting with a letter or underscore and consisting of letters, digits, and underscores.
  • Operators: Symbols are utilized as operators to perform various operations on data. For instance, arithmetic operators (+, -, *, /), logical operators (&&, ||, !), and relational operators (==, !=, <, >) are symbols used for calculations and decision-making.
  • Delimiters: Symbols serve as delimiters to mark the beginning and end of code blocks or specific sections. Examples include braces ({ }), parentheses (()), and semicolons (;).
  • Comments: Symbols are used to create comments in Java code, allowing developers to add explanatory text that is ignored by the compiler. The double forward slash (//) denotes a single-line comment, while /* and */ enclose multi-line comments.
  • Special Characters: Symbols include special characters, such as escape sequences (\n, \t, etc.), which represent non-printable characters and formatting options in strings and output.

Understanding and using symbols correctly is essential for writing valid and expressive Java code that can be compiled and executed successfully.

Logicmojo Learning Library