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.
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.
The types below informs us about the whole different types of operators offered by the Java programming language.
Unary Operators
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Shift Operators
Ternary Operators
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). |
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 ); } }
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.
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.
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); } }
15 -5 50 0 5
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. |
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 } }
true false true false false true
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. |
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)); } }
(10 > 5) && (15 > 10) returns true as both (10 > 5) and (15 > 10) are true.
(10 > 5) && (15 < 10) returns false as the expression (15 < 10) is false.
(10 < 5) || (15 > 10) returns true as the expression (15 > 10) is true.as
(10 < 5) || (15 < 10) returns false as both (10 < 5) and (15 < 10) are false.
!(10 == 5) returns true as 10 == 5 is false.
!(10 > 5) returns false as 10 > 5 is true.
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 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. |
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
yx|y = 0011 1111
x^y = 0011 1011
~x = 0011 0001
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 } }
4 63 59 -46
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 |
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 } }
15 15 10 50 10 0 5
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. |
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 } }
40 2
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.
variable x = (condition) ? Exp1 (if condition is true) : Exp2( if condition is false)
The value returned by either expression is stored in variable.
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 ); } }
The greater value is : 10
It's solely used for object reference variables. It determines whether or not the object is of the interface or class type.
( Object reference variable ) instanceof (class/interface type)
The value returned by either expression is stored in variable.
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 ); } }
The condition is true
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.
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,
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 | Operator | Associativity |
---|---|---|
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 |
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.
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.
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.
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.
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.
Comparisons and Conditions: Relational operators (e.g., <, >, ==, !=) enable easy comparisons between variables, which are essential for decision-making and branching in Java programs.
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.
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.
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.
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.
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.
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.
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!
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:
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:
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:
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:
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:
Understanding and using symbols correctly is essential for writing valid and expressive Java code that can be compiled and executed successfully.