Arithmetic,Relational and Logical Operators in Java

Arithmetic Operators in Java



Arithmetic operators are the fundamental building blocks for performing mathematical calculations in Java programs. They work on numeric data types like `int`, `double`, and `float` to perform basic arithmetic operations like addition, subtraction, multiplication, and division.

Key Points About Arithmetic Operators

  • Types:
    • Binary Operators: These operators require two operands (values) on either side of the symbol, such as `+`, `-`, `*`, and `/`.
    • Unary Operators:These operators work with a single operand, like `++` (increment) and `--` (decrement). (We'll cover these in a separate discussion)
  • Functionality: They perform calculations on numeric values and return a result of the same numeric type (except for division by zero).
  • Common Uses:
    • Performing calculations in programs involving finances, scientific computations, physics simulations, and game development.
    • Updating counters, calculating scores, processing statistical data, and adjusting values based on conditions.

Basic Arithmetic Operators

The following table summarizes the basic arithmetic operators in Java:

Basic Arithmetic Operators
Operator Description Example
+ Addition int sum = 10 + 5;
- Subtraction int difference = 20 - 7;
* Multiplication double product = 3.14 * 2;
/ Division float quotient = 10 / 3; (Be mindful of integer division)
% Modulo (Remainder) int remainder = 11 % 3;

Important Note: Division with integers (`int / int`) performs integer division, discarding any fractional part. For floating-point division (`double / double` or `float / float`), you get the decimal result.

By effectively using arithmetic operators, you can manipulate numerical data in your Java programs to achieve various functionalities.

Relational Operators in Java



Relational operators are the workhorses for comparing values in Java programs. They determine the relationship between two operands, which can be numeric values, characters, or objects. Based on this comparison, they return a boolean value (true or false).

Key Points About Relational Operators

  • Types: Java provides six relational operators:
    • == (equal to)
    • != (not equal to)
    • < (less than)
    • > (greater than)
    • <= (less than or equal to)
    • >= (greater than or equal to)
  • Functionality: They compare two operands and return true if the condition is met, false otherwise.
  • Common Uses:
    • Implementing conditional statements (if-else, switch) to control program flow based on comparisons.
    • Validating user input, checking data integrity, and performing comparisons in loops.

Relational Operators in Action

The following table summarizes the relational operators and their usage:

Operator Description Example
== Equal to int num1 = 5; int num2 = 5; if (num1 == num2) { ... }
!= Not equal to char letter = 'A'; if (letter != 'B') { ... }
< Less than double temp = 20.5; if (temp < 30) { ... }
> Greater than int age = 18; if (age > 13) { ... }
<= Less than or equal to String name = "Alice"; if (name.length() <= 10) { ... }
>= Greater than or equal to float grade = 85.0f; if (grade >= 70) { ... }

Important Notes:

  • Relational operators are most effective with numeric data types (int, double, float) and characters.
  • For Strings, use comparison methods like equals() or compareTo() for content comparison.
  • Be mindful when comparing objects with relational operators, as they might compare object references by default instead of content.

Logical Operators in Java

Logical operators are the building blocks for combining conditional statements in Java programs. They act like logical switches, manipulating boolean values (true or false) to create more complex conditions.

Key Points About Logical Operators

  • Types: Java provides three primary logical operators:
    • && (AND)
    • || (OR)
    • ! (NOT)
  • Functionality: They operate on boolean values and return a boolean result based on the logical relationship between the operands.
  • Common Uses:
    • Constructing complex conditional statements (if-else, switch) with multiple conditions.
    • Validating user input with multiple criteria.
    • Controlling program flow based on combined boolean expressions.

Understanding Logical Operators

The following table summarizes the logical operators and their usage in Java programs:

Logical Operators
Operator Description Example
&& (AND) Returns true only if both operands are true. int age = 20; boolean employed = true; if (age >= 18 && employed) { ... }
|| (OR) Returns true if at least one operand is true. char initial = 'A'; String city = "New York"; if (initial == 'A' || city.equals("London")) { ... }
! (NOT) Inverts the logical state of the operand. boolean isNight = false; if (!isNight) { ... } (Equivalent to: if (isNight == false))

Important Notes:

  • Logical operators follow a specific order of evaluation (precedence). NOT has higher precedence than AND and OR. Use parentheses for clarity when combining operators (e.g., (age >= 18) && employed).
  • Logical operators can exhibit short-circuit evaluation. In AND, if the first operand is false, the second operand isn't evaluated to improve efficiency. Similarly, in OR, if the first operand is true, the second operand isn't evaluated.

Program to divide two integers


    public class DivideNumbers {

      public static void main(String[] args) {
        int num1 = 5;
        int num2 = 2;
    
        // Integer division discards the remainder
        int result = num1 / num2;
    
        System.out.println("The result of dividing " + num1 + " by " + num2 + " is: " + result);
      }
    }
  

Program to divide two integers and type cast the result


    public class DivideNumbers {

      public static void main(String[] args) {
        int num1 = 5;
        int num2 = 2;
        double result = (double) num1 / num2;
        System.out.println("The result of dividing " + num1 + " by " + num2 + " is: " + result);
      }
    }
  

Program to find the greatest of two numbers


  public class GreatestNumber {

    public static void main(String[] args) {
      int num1 = 3;
      int num2 = 4;
      if (num1 > num2) {
        System.out.println(num1 + " is greater than " + num2);
      } else {
        System.out.println(num2 + " is greater than or equal to " + num1);
      }
    }
  }

Program to check if a number is greater than other two numbers


  public class CompareVariables {

    public static void main(String[] args) {
      int var1 = 10;
      int var2 = 5;
      int var3 = 8;
      // Using logical AND operators 
      if (var1 > var2 && var1 > var3) {
        System.out.println("var1 is greater than both var2 and var3.");
      } else {
        System.out.println("var1 is not greater than both var2 and var3.");
      }
    }
  }

Consider three variables var1,var2 and var3, if var1 is greater than var2 or var3 then print the message "its working" or else display "not working"


  public class CheckCondition {

    public static void main(String[] args) {
      int var1 = 7;
      int var2 = 5;
      int var3 = 10;
  
      // Using logical OR operator 
      if (var1 > var2 || var1 > var3) {
        System.out.println("its working");
      } else {
        System.out.println("not working");
      }
    }
  }  

Program for demo of NOT Operator


package javaprogrammingdemo;
public class javalabclass{
  public static void main(String args[]) 
  boolean isNight = false; 
  int age = 20;
  int minAgeToVote = 18;

  // Scenario 1: Checking the opposite of a boolean variable
  if (!isNight) { // equivalent to if (isNight == false)
    System.out.println("It's daytime!");
  }

  // Scenario 2: Negating a condition
  if (!(age < minAgeToVote)) { // equivalent to if (age >= minAgeToVote)
    System.out.println("You are eligible to vote.");
  }
}