Mastering the Magic: Operators in Java

Mastering the Magic: Operators in Java

Hey everyone,

Welcome back to our coding journey! Last time, we explored the power of variables and data types in Java. This week, we'll delve into the tools that help us manipulate and transform data: operators!


Operators: The Building Blocks of Calculations

Think of operators as the magic wands of Java. They allow us to perform calculations, compare values, and even combine data in different ways. Here are some common operators you'll encounter:

  • Arithmetic Operators: +: Addition (e.g., 5 + 3 = 8) -: Subtraction (e.g., 10 - 2 = 8) : Multiplication (e.g., 4 5 = 20) /: Division (e.g., 12 / 3 = 4)
  • Comparison Operators: ==: Equal to (e.g., 7 == 7 is true) !=: Not equal to (e.g., 5 != 8 is true) <: Less than (e.g., 2 < 5 is true) >: Greater than (e.g., 10 > 3 is true)
  • Logical Operators: &&: And (e.g., (5 > 3) && (7 == 7) is true) ||: Or (e.g., (age >= 18) || (hasStudentID == true) is true)


Putting it all Together:

Let's see how we can use operators in our code:

public class Calculations {

  public static void main(String[] args) {
    int num1 = 15;
    int num2 = 5;

    int sum = num1 + num2; // Addition
    int difference = num1 - num2; // Subtraction
    int product = num1 * num2; // Multiplication
    double quotient = (double) num1 / num2; // Casting to double for decimal result

    System.out.println("The sum of " + num1 + " and " + num2 + " is: " + sum);
    System.out.println("The difference of " + num1 + " and " + num2 + " is: " + difference);
    System.out.println("The product of " + num1 + " and " + num2 + " is: " + product);
    System.out.println("The quotient of " + num1 + " and " + num2 + " is: " + quotient);
  }
}
        
Pro Tip:
Remember the order of operations (PEMDAS) when using multiple operators in a single expression. Parentheses can be used to control the order of evaluation.


This week, experiment with different operators in your code. Try combining them to create more complex expressions and calculations. Explore how operators can be used to compare values and make decisions within your programs.

In the next newsletter, we'll dive into the world of control flow with conditional statements. This will allow us to make our programs more dynamic and interactive!

Happy coding!

Ravi Pratap Singh

To view or add a comment, sign in

More articles by Ravi Pratap Singh

Explore content categories