Java - Basic Operators

Welcome, future Java programmers! Today, we're going to dive into the exciting world of Java operators. Don't worry if you've never written a line of code before – we'll start from the very beginning and work our way up. By the end of this lesson, you'll be manipulating data like a pro!

Java - Basic Operators

What are Operators?

Before we jump in, let's understand what operators are. In programming, operators are special symbols that tell the computer to perform specific mathematical or logical manipulations. Think of them as the verbs in a sentence – they're the action-takers!

Java Arithmetic Operators

Let's start with the most familiar operators – arithmetic operators. These are the ones you've been using since elementary school!

Addition (+)

int apples = 5;
int oranges = 3;
int totalFruit = apples + oranges;
System.out.println("Total fruit: " + totalFruit);

This code will output: Total fruit: 8

Here, we're using the + operator to add apples and oranges. (See? In programming, we can add apples and oranges!)

Subtraction (-)

int startingMoney = 100;
int spentMoney = 25;
int remainingMoney = startingMoney - spentMoney;
System.out.println("Money left: $" + remainingMoney);

Output: Money left: $75

The - operator subtracts one value from another.

Multiplication (*)

int widgetPrice = 5;
int widgetQuantity = 7;
int totalCost = widgetPrice * widgetQuantity;
System.out.println("Total cost: $" + totalCost);

Output: Total cost: $35

The * operator multiplies two values.

Division (/)

int pizzaSlices = 8;
int people = 3;
int slicesPerPerson = pizzaSlices / people;
System.out.println("Slices per person: " + slicesPerPerson);

Output: Slices per person: 2

The / operator divides one value by another. Note that when dividing integers, Java rounds down to the nearest whole number.

Modulus (%)

int cookiesLeft = 10;
int peopleWantingCookies = 3;
int leftoverCookies = cookiesLeft % peopleWantingCookies;
System.out.println("Cookies left over: " + leftoverCookies);

Output: Cookies left over: 1

The % operator gives you the remainder after division. It's super useful for determining if numbers are even or odd, or for cycling through a range of values.

Java Relational Operators

Relational operators compare two values and return a boolean result (true or false). They're essential for making decisions in your code.

Equal to (==)

int age = 18;
boolean canVote = (age == 18);
System.out.println("Can this person vote? " + canVote);

Output: Can this person vote? true

The == operator checks if two values are equal.

Not equal to (!=)

String weather = "sunny";
boolean stayInside = (weather != "sunny");
System.out.println("Should I stay inside? " + stayInside);

Output: Should I stay inside? false

The != operator checks if two values are not equal.

Greater than (>) and Less than (<)

int playerScore = 85;
int highScore = 90;
boolean newHighScore = (playerScore > highScore);
System.out.println("New high score achieved: " + newHighScore);

Output: New high score achieved: false

The > operator checks if the left value is greater than the right, while < does the opposite.

Greater than or equal to (>=) and Less than or equal to (<=)

int requiredAge = 18;
int personAge = 18;
boolean canEnter = (personAge >= requiredAge);
System.out.println("Can the person enter? " + canEnter);

Output: Can the person enter? true

These operators check if a value is greater/less than or equal to another value.

Java Logical Operators

Logical operators allow you to combine multiple conditions.

AND (&&)

boolean hasTicket = true;
boolean hasID = true;
boolean canAttendConcert = hasTicket && hasID;
System.out.println("Can attend the concert: " + canAttendConcert);

Output: Can attend the concert: true

The && operator returns true only if both conditions are true.

OR (||)

boolean isWeekend = true;
boolean isHoliday = false;
boolean canSleepIn = isWeekend || isHoliday;
System.out.println("Can sleep in: " + canSleepIn);

Output: Can sleep in: true

The || operator returns true if at least one condition is true.

NOT (!)

boolean isRaining = false;
boolean shouldTakeUmbrella = !isRaining;
System.out.println("Should take umbrella: " + shouldTakeUmbrella);

Output: Should take umbrella: true

The ! operator inverts a boolean value.

The Assignment Operators

We've been using the basic assignment operator = throughout our examples. But Java has some shorthand operators that combine assignment with other operations.

Addition assignment (+=)

int score = 0;
score += 10; // This is equivalent to: score = score + 10;
System.out.println("Current score: " + score);

Output: Current score: 10

Other assignment operators

Java also has -=, *=, /=, and %= which work similarly.

Java Operators Precedence & Associativity

Just like in math, Java operators have an order of precedence. For example:

int result = 5 + 3 * 2;
System.out.println("Result: " + result);

Output: Result: 11

The multiplication happens before the addition, just like in regular math.

Here's a simplified table of operator precedence (from highest to lowest):

Precedence Operator
1 * / %
2 + -
3 < > <= >=
4 == !=
5 &&
6
7 =

Remember, you can always use parentheses to specify the order of operations explicitly:

int result = (5 + 3) * 2;
System.out.println("Result with parentheses: " + result);

Output: Result with parentheses: 16

And there you have it! You've just taken your first steps into the world of Java operators. These little symbols might seem simple, but they're the building blocks of all the amazing things you'll create with Java. Keep practicing, and soon you'll be combining these operators to solve complex problems and build incredible programs. Happy coding!

Credits: Image by storyset