Basic Operators in Java

This article covers basic operators of Java syntax, and how they function. By thorough discussion and coding examples, you’ll be able to use basic operators in your programs like a pro.

What are basic operators?

Java provides different sets of operators to perform simple computations like addition/ subtraction and other advanced operators for decision-making or individual bitwise calculations.

Here are some major categories of operators

  • Arithmetic Operators (+, -, *, /)
  • Relational Operators (==, !=)
  • Logical Operators (&&, ||)
  • Assignment Operators (=, +=, -=)
  • Unary Operators (pre/post-fix)
  • Shift Operators (>>, << )
  • Bitwise Operators (&, |, ^)
  • Ternary/Conditional Operator (?:)
  • Misc Operators

The scope of this article encompass arithmetic, relational and logical operators only.

Arithmetic Operators

You can use basic arithmetic operators to perform a mathematical calculation and impact the value of any variable. Let’s see how it works in Java.

package com.basicoperators.core;

public class ArithmeticOperators {
    public static void main(String[] args) {
        // Addition 
        int apples = 5;
        int oranges = 7;
        int totalFruits = apples + oranges;

        System.out.println("\n-------------Addition---------------- " );
        System.out.println("Apples: " + apples);
        System.out.println("Oranges: " + oranges);
        System.out.println("Total Fruits: " + totalFruits);

        // Subtraction      
        int totalBananas = 24;
        int bananasSold = 12;
        int bananasLeft = totalBananas - bananasSold;

        System.out.println("\n----------------Subtraction--------------- " );
        System.out.println("Total Bananas: " + totalBananas);
        System.out.println("Bananas Sold: " + bananasSold);
        System.out.println("Bananas Left: " + bananasLeft);

        // Multiplication   
        int weeks = 3;
        int daysInAWeek = 7;
        int totalNumberOfDays = weeks * daysInAWeek;

        System.out.println("\n--------------Multiplication-------------- " );
        System.out.println("Days In A Week: " + daysInAWeek);
        System.out.println("Days In A Week: " + daysInAWeek);
        System.out.println("Total Number Of Days: " + totalNumberOfDays);

        // Division
        int totalMinutesConsumed = 420;
        int minutesInOneHour = 60;
        int numOfHours = totalMinutesConsumed / minutesInOneHour;

        System.out.println("\n----------------Division---------------- " );

        System.out.println("Total Minutes: " + totalMinutesConsumed);
        System.out.println("Minutes In One Hour: " + minutesInOneHour);
        System.out.println("Num Of Hours: " + numOfHours);    
    }
}

Output

----------------------Addition---------------------- 
Apples: 5
Oranges: 7
Total Fruits: 12

---------------------Subtraction--------------------- 
Total Bananas: 24
Bananas Sold: 12
Bananas Left: 12

--------------------Multiplication------------------- 
Days In A Week: 7
Days In A Week: 7
Total Number Of Days: 21

----------------------Division---------------------- 
Total Minutes Consumed: 420
Minutes In One Hour: 60
Num Of Hours: 7

Relational Operators

As the name implies, relational operators define the relationship of one instance with another. This means you can compare two numbers and see what relationship do they share. If they are equal to each other, one is greater than or smaller than the other number. Like 2 is less than 3. According to Java syntax, both instances should be of the same data type. For example, you can not compare if an integer is less than a string. Here is a small snippet explaining how you can use basic relational operators in Java.

package com.basicoperators.core;

public class RelationalOperators {
    public static void main(String[] args) {
        int even = 2;
        int odd = 3;

        System.out.println("Even = " + even);
        System.out.println("Odd = " + odd);

        // prints if even is equal to odd
        boolean check = even == odd;
        System.out.println("Is Even equal to Odd? " + check);

        // prints if even is not equal to odd
        check = even != odd;
        System.out.println("Is Even not equal to Odd? " + check);

        // prints if even is greater than odd
        check = even > odd;
        System.out.println("Is Even greater than Odd? " + check);

        // prints if even is less than odd
        check = even < odd;
        System.out.println("Is Even less than Odd? " + check);

        // prints if even is greater than equal to odd
        check = even >= odd;
        System.out.println("Is Even greater than equal to Odd? " + check);

        // prints if even is less than equal to odd
        check = even <= odd;
        System.out.println("Is Even less than equal to Odd? " + check);
    }
}

Output

Even = 2
Odd = 3
Is Even equal to Odd? false
Is Even not equal to Odd? true
Is Even greater than Odd? false
Is Even less than Odd? true
Is Even greater than equal to Odd? false
Is Even less than equal to Odd? true

Logical Operators

Logical Operators in Java are used for decision-making. They allow the programmer to test if the combination of given expressions are true or false. Based on the result of your expression, you can make a decision.

  • AND – returns “true” only if both expressions are true
  • OR – returns “true” if any of the given expressions is true
  • NOT – returns the “inverse” of any given boolean expression

For your better understanding, let’s look at the following snippet.

package com.basicoperators.core;

public class LogicalOperators {
    public static void main(String[] args) {
        String myPet1 = "doggo";
        String myPet2 = "kitty";

        System.out.println("Pet1: " + myPet1);
        System.out.println("Pet2: " + myPet2);

        // implements AND
        boolean check = myPet1.equals("doggo") && myPet2.equals("kitty");
        // returns true only when both conditions are true
        System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);

        check = myPet1.equals("dog") && myPet2.equals("kitty");
        // returns "false" even if single condition is false 
        // remember these conditions are case sensitive
        System.out.println("Does my first pet name \"dog\", and second one \"kitty\"? " + check);

        // implements OR
        check = myPet1.equals("doggo") || myPet2.equals("lion");
        // returns "true" even when single condition is true
        System.out.println("Does any of my pet name \"doggo\"? " + check);

        check = myPet1.equals("cat") || myPet2.equals("tiger");
        // returns "false" because both conditions are false
        System.out.println("Does any of my pet name \"tiger\"? " + check);

        // implements NOT
        check = !(myPet1.equals("bingo") && myPet2.equals("kate"));
        // returns "true" when both conditions are true (inverse of statement)
        System.out.println("Does my first pet name \"bingo\", and second one \"kate\"? " + check);

        check = !(myPet1.equals("doggo") && myPet2.equals("kitty"));
        // returns "false" because both conditions are true
        System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);
    }
}

Output

Pet1: doggo
Pet2: kitty
Does my first pet name "doggo", and second one "kitty"? true
Does my first pet name "dog", and second one "kitty"? false
Does any of my pet name "doggo"? true
Does any of my pet name "tiger"? false
Does my first pet name "bingo", and second one "kate"? true
Does my first pet name "doggo", and second one "kitty"? false

Conclusion

The basic operators in Java are pretty simple to learn and easy to use. You might get overwhelmed by studying the different operators all at once. However, we recommend you practicing one set at a time. This way, you’ll master all of them soon. As always, you’re welcome to plug-in in case of any confusion. Happy learning!

How do I use the diamond syntax?

In Java 7 a new feature called diamond syntax or diamond operator was introduced. This diamond syntax <> simplify how we instantiate generic type variables. In the previous version of Java when declaring and instantiating generic types we’ll do it like the snippet below:

List<String> names = new ArrayList<String>();
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

As you can see in the snippet, we were repeating our self by defining the generic type two times. We define the object type we’ll be stored in the List and the Map on both left and the right side. By using the diamond syntax the compiler will infer the type of the right side expression argument automatically. So in Java 7 we can write the above code snippet like this:

List<String> names = new ArrayList<>();
Map<String, List<Integer>> map = new HashMap<>();

This make our code simpler and more readable, and by using the diamond syntax the compiler will ensure that we have the generic type-safe checking available in our code. This will make any error due to type incompatibility captured at compile time.

How do I use the || operator in Java?

The || operator or conditional OR operator operates on two boolean expressions. This operator exhibit “short-circuiting” behavior, which means that the second operand is evaluated only if needed.

The || operator evaluate only boolean values. For an OR (||) expression it will return true if either of the operand is true. If the first operand resolves true, then the second operand will not evaluate, because the complete expression will return true.

package org.kodejava.basic;

public class ConditionalORDemo {
    public static void main(String[] args) {
        // the second operand (5<3) is not evaluated, because the
        // first operand return true, the result of complete
        // expression will be true
        boolean a = (1 == 1) || (5 < 3);

        // the first operand return false, the second operand is
        // evaluated to check the result of the second expression.
        // If the second operand resolves to true, the complete
        // expression return true, otherwise return false.
        boolean b = (5 < 3) || (2 == 3);
        boolean c = (5 < 3) || (1 == 1);

        System.out.println("result a: " + a);
        System.out.println("result b: " + b);
        System.out.println("result c: " + c);
    }
}

The program prints the following output:

result a: true
result b: false
result c: true

How do I use the boolean negation (!) operator in Java?

The ! operator is a logical compliment operator. The operator inverts the value of a boolean expression.

package org.kodejava.basic;

public class NegationOperator {
    public static void main(String[] args) {
        // negate the result of boolean expressions
        boolean negate = !(2 < 3);
        boolean value = !false;

        System.out.println("result: " + negate);
        System.out.println("value : " + value);
    }
}

Here is the result of the program:

result: false
value : true

How do I use the relational operator in Java?

Relational operators used to compare any combination of integers, floating-point numbers, or characters. The result of relational operators is always in a boolean value, true or false. It is mostly used in an if statement test.

There are four relational operators in Java:

  • > greater than
  • >= greater than or equal to
  • < less than
  • <= less than or equal to
package org.kodejava.basic;

public class RelationalDemo {
    public static void main(String[] args) {
        int value1 = 10, value2 = 25;
        int age = 15;
        double salary = 1000d;
        char char1 = 'd', char2 = 'f';

        if (value1 > value2) {
            System.out.format("%d is greater than %d %n", value1, value2);
        } else {
            System.out.format("%d is greater than %d %n", value2, value1);
        }

        if (age >= 12) {
            System.out.format("Hey, I am not a kid anymore %n");
        }

        if (char1 < char2) {
            System.out.format("%c is less than %c %n", char1, char2);
        } else {
            System.out.format("%c is less than %c %n", char2, char1);
        }

        if (salary <= 3000d) {
            System.out.println("Entry-level Staff");
        }
    }
}

An here are the result of the program:

25 is greater than 10 
Hey, I am not a kid anymore 
d is less than f 
Entry-level Staff