Operators and Expressions

Learn how to use Operators and Expressions in Java with this hands-on exercise. Discover how arithmetic, logical, relational, and assignment operators work to perform calculations and make decisions in your code. Master the use of expressions in Java and improve your programming logic with examples and real-world practice.

Topic

Java Fundamentals

Java Exercise

In this exercise, you will create a Java program that uses various Operators and Expressions to perform calculations and evaluate conditions. You will learn to work with:

  • Arithmetic operators: addition, subtraction, multiplication, division, and modulo.
  • Relational operators: comparing values ​​such as greater than, less than, and equality.
  • Logical operators: combining conditions with && (AND) and || (OR).
  • Assignment operators: modifying and updating variable values.

Instructions:

  1. Declare two numeric variables and perform arithmetic operations on them.
  2. Use relational operators to compare values ​​and display the results.
  3. Apply logical operators to evaluate combined conditions.
  4. Display the results to the console using System.out.println().

This exercise will help you understand the use of Operators and Expressions in Java, which are essential for programming logic and decision-making in code.


public class JavaOperators {
    public static void main(String[] args) {
        // Variable declaration
        int a = 10;
        int b = 5;

        // Arithmetic operators
        int sum = a + b;
        int subtract = a - b;
        int multiplication = a * b;
        double division = (double) a / b;
        int modulo = a % b;

        // Relational operators
        boolean isGreater = a > b;
        boolean isEqual = a == b;

        // Logical operators
        boolean condition1 = (a > 0) && (b > 0);
        boolean condition2 = (a < 0) || (b < 0);

        // Display results in console
        System.out.println("Sum: " + sum);
        System.out.println("Subtraction: " + subtract);
        System.out.println("Multiplication: " + multiplication);
        System.out.println("Division: " + division);
        System.out.println("Modulo: " + modulo);
        System.out.println("Is A greater than B?: " + isGreater);
        System.out.println("Is A equal to B?: " + isEqual);
        System.out.println("Are both numbers positive?: " + condition1);
        System.out.println("Is either number negative?: " + condition2);
    }
}

 Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Modulo: 0
Is A greater than B?: true
Is A equal to B?: false
Are both numbers positive?: true
Is either number negative?: false

This code demonstrates the use of arithmetic, relational, and logical operators in Java, allowing you to understand how to perform calculations and evaluate conditions in a program.


 Share this JAVA exercise