Home Java Tutorial Java Operators

Java Operators

by Anup Maurya
5 minutes read

Java operators are symbols that are used to perform operations on variables and values. In this tutorial, we will discuss the different types of Java operators and how to use them.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, division, and modulus. Here are some examples:

  • Addition: int sum = a + b;
  • Subtraction: int diff = a - b;
  • Multiplication: int product = a * b;
  • Division: int quotient = a / b;
  • Modulus: int remainder = a % b;

Comparison Operators

Comparison operators are used to compare two values and return a boolean value (true or false). Here are some examples:

  • Equal to: boolean isEqual = (a == b);
  • Not equal to: boolean isNotEqual = (a != b);
  • Greater than: boolean isGreaterThan = (a > b);
  • Less than: boolean isLessThan = (a < b);
  • Greater than or equal to: boolean isGreaterOrEqual = (a >= b);
  • Less than or equal to: boolean isLessOrEqual = (a <= b);

Logical Operators

Logical operators are used to combine multiple boolean expressions and return a boolean value. Here are some examples:

  • AND: boolean result = (expression1 && expression2);
  • OR: boolean result = (expression1 || expression2);
  • NOT: boolean result = !(expression);

Assignment Operators

Assignment operators are used to assign values to variables. Here are some examples:

  • Simple assignment: int x = 10;
  • Add and assign: x += 5; (Equivalent to x = x + 5;)
  • Subtract and assign: x -= 5; (Equivalent to x = x - 5;)
  • Multiply and assign: x *= 5; (Equivalent to x = x * 5;)
  • Divide and assign: x /= 5; (Equivalent to x = x / 5;)
  • Modulus and assign: x %= 5; (Equivalent to x = x % 5;)

Bitwise Operators

Bitwise operators are used to perform bitwise operations on integer types. Here are some examples:

  • Bitwise AND: int result = a & b;
  • Bitwise OR: int result = a | b;
  • Bitwise XOR: int result = a ^ b;
  • Bitwise NOT: int result = ~a;
  • Left shift: int result = a << 2; (Shifts the bits of a by 2 positions to the left)
  • Right shift: int result = a >> 2; (Shifts the bits of a by 2 positions to the right)

Conditional Operator

The conditional operator is used to assign a value to a variable based on a boolean expression. Here is an example:

  • int max = (a > b) ? a : b; (If a is greater than b, assign the value of a to max, otherwise assign the value of b to max)

In conclusion, Java operators are an essential part of the Java programming language. They allow us to perform mathematical, logical, and bitwise operations on variables and values. By mastering the use of Java operators, we can write more efficient and concise code.

related posts

Leave a Comment