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!

Why do I get ArrayIndexOutOfBoundsException in Java?

The ArrayIndexOutOfBoundsException exception is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

Array with 10 elements

For example see the code snippet below:

String[] vowels = new String[]{"a", "i", "u", "e", "o"}
String vowel = vowels[10]; // throws the ArrayIndexOutOfBoundsException

Above we create a vowels array with five elements. This will make the array have indexes between 0..4. On the next line we tried to access the tenth element of the array which is illegal. This statement will cause the ArrayIndexOutOfBoundsException thrown.

We must understand that arrays in Java are zero indexed. The first element of the array will be at index 0 and the last element will be at index array-size - 1. So be careful with your array indexes when accessing array elements. For example if you have an array with 5 elements this mean that the index of the array is from 0 to 4.

If you are trying to iterate an array using for loop. Make sure the index start from 0 and execute the loop while the index is less than the length of the array, you can get the length of the array using the array length property. Let’s see the code snippet below:

for (int i = 0; i < vowels.length; i++) {
    String vowel = vowels[i];
    System.out.println("vowel = " + vowel);
}

Or if you don’t need the index you can simplify your code using the for-each or enhanced for-loop statement instead of the classic for loop statement as shown below:

for (String vowel : vowels) {
    System.out.println("vowel = " + vowel);
}

Java SE Installation Tutorial

Summary: This tutorial is about Java Development Kit (JDK) Standard Edition installation guide. After reading and executing this tutorial you will be able to install the JDK and setting the basic configuration for running the Java compiler from the command line. You will also learn how to create, compile and run a simple Hello World program written in Java.

Download The JDK

When this tutorial is written, the latest JDK is version 7 Update 45. To download the Java SE Development Kit 7 (JDK 7) click to following URL: Java SE Downloads. Make sure you choose the Windows version and download the JDK and not the JRE. The JDK installer will have the JRE included.

Installing The JDK

After downloading you will have a file called jdk-7u45-windows-i586.exe. Executing this file, either by double-click the file or running it from the command prompt, will begin the installation process. You will see the following screens during the installation process:

Installation Wizard Welcome Screen

Installation Wizard Welcome Screen

To continue the installation click the Next button shown in the screen above. This action will bring you to the feature’s selection screen in the installation wizard shown below.

Features Selection

Features Selection

In the feature’s selection screen above you will be able to choose which features to install. For the simplicity of this tutorial we will choose to install the entire features. We will also use the default installation path. In Windows operating system the default path is C:\Program Files (x86)\Java\jdk1.7.0_45. Click the Next button to continue to the next step.

Installation Progress

Installation Progress

The screen above shows the progress status of the JDK installation. Depending on your computer speed this process may take a couple of minutes to finish. Wait for the next screen to show up.

JRE Installation Screen

JRE Installation Screen

As stated above that the JRE is included within the JDK installer, the screen above show you the JRE installation wizard. We will use the default path as shown above C:\Program Files (x86)\Java\jre7. Click the Next button to continue to the next step.

JRE Installation Progress

JRE Installation Progress

The screen above shows the status of the JRE installation. Depending on your computer speed this process may take some other minutes to complete. When the JRE installation complete you will see the next screen.

JDK Installation Completed

JDK Installation Completed

Seeing the screen above means that your JDK installation is completed. Click the Finish button to exit the installation Wizard.

Configuring The JDK

Now you have the JDK installed on your system. Configuring the JDK so that you can run the javac and java commands from the command prompt is another important steps. A lot of beginners faced with a problem that the javac command is not recognized because they did not configure the path correctly. To validate your installation type the javac command in the command prompt. At first, you will see the following screen as the command output.

javac command is not recognized

javac command is not recognized

To make the javac command run properly you need to update the PATH environment variable to include the Java binary installation path. The following steps will show you how to configure the PATH environment variable.

  • Open your Windows Explorer, you can use the Windows + E shortcut.
  • Right click on Computer icon and choose the Properties menu.
  • Click Advanced system setting from the Task list.
  • In the System Properties window choose the Advanced tab.
  • Click the Environment Variables button.
  • In the Environment Variables windows you will see two sections. User variables and System variables.
  • Find the Path variable and click the Edit button.
  • In the Edit User Variable screen, update the current variable value by adding the path to JDK bin folder, in our case the path will be C:\Program Files (x86)\Java\jdk1.7.0_45\bin;. You should add this information at the beginning at the beginning to make sure it will be picked first.
  • Press the OK button to update the User Variable.
  • Press the OK button to finish the Environment Variables setting.
  • Press the OK button on the System Properties window to close it.

Now you can open a new command prompt window and type the javac command. You will see that the javac command is now run as expected. You can type javac -version to check the version of your JDK.

Java Command Recognized

Java Command Recognized

Creating The HelloWorld.java

Now you have the JDK installed and configured properly. Let’s now create our first Java program, the famous Hello World program. Let’s begin.

  • Open a command prompt window.
  • Create a directory C:\HelloWorld\src.
  • Go to the src directory and create another directory call program.
  • Go to the program directory.
  • Create the HelloWorld.java source file by typing notepad.exe HelloWorld.java.
  • The Notepad program will show a dialog saying that the HelloWorld.java file is not found.
  • Press the Yes button for creating the file.
  • Type the following code in the Notepad editor.
package program;

public class HelloWorld {
   public static void main(String[] args) {
       System.out.println("Hello World");
   }
}
  • Click the Save menu to save your program.
  • Click the Exit menu to exit from the Notepad program.
  • Type the dir command, and you will see that you have created a file called HelloWorld.java.

Compiling Java Source File

Up to this step you have created your first Java program. Before running the program you need to compile it. The compilation process compiles your Java source file into something called the Java bytecode. The bytecode is an intermediate language that makes the Java program portable across different platform.

To compile the program do the following step:

  • Go to the C:\HelloWorld\src\program directory.
  • Type javac HelloWorld.java to compile the source code.
  • A successful compilation will produce a HelloWorld.class file. This class file is your binary HelloWorld program, and it is ready to be executed.
Compiling Hello World

Compiling Hello World

Running the Program

Now you are in the final step of the tutorial. Running the HelloWorld program. Here are the final step you need to run:

  • Go to the C:\HelloWorld\src directory.
  • Type java program.HelloWorld without the .class extension to run the program.
  • You will see that the Hello World string printed on the screen.
Running Hello World

Running Hello World

That’s all for now, see you on another tutorial.

How do I set up JAVA_HOME and Path variables in Windows?

Setting up a JAVA_HOME and Path variables is the second thing you’ll need to do after installing a JDK (Java Development Kit). Although this is not required by Java itself, it is commonly use by other application. For instance then Apache Tomcat web application server and other application server will need it. Or we might need it if we want to compile or running our Java classes from the command prompt. It helps us to organize the default JDK and the execution path.

So here are the steps that we’ll need to do to configure the JAVA_HOME and Path variable on a Windows operating system.

Step 1. Finding the location of our JDK installation directory. If we already know where we have installed the JDK continue to the Step 2.

  1. The JDK usually installed in the C:\Program Files\Java directory by default.
  2. Under this directory we can find one or more versions of installed JDK, for examples I have jdk-14 and jdk-17. Just choose the default one we’re going to use.

Step 2. Setting JAVA_HOME variable

After we know the location of your JDK installation, we can copy the directory location from the Windows Explorer address bar.

  1. Open Windows Explorer
  2. Right-Click the Computer and select the Properties menu.
  3. Click Advanced system settings and the System Properties windows will be shown.
  4. Select the Advance tab.
  5. Click the Environment Variables button.
  6. A new Environment Variables window will be shown.
  7. Under the System Variables, click the New button to create a new environment variable.
  8. Enter the variable name as JAVA_HOME, all letters are in uppercase.
  9. In the variable value enter the JDK installation path you’ve copy above.
  10. Click OK.

Step 3. Setting the Path variable

After we’ve set the JAVA_HOME variable, now we can update the Path variable.

  1. In the Environment Variables window, under the System Variables section find a variable named Path.
  2. If we don’t have the Path variable we need to add one using the New button.
  3. If we already have the Path variable we’ll need to update its value, click Edit button to update.
  4. Add %JAVA_HOME%\bin; to the beginning of the Path variable value.
  5. Press OK to when we are done.
  6. Press another OK to close the Environment Variables window.

Step 4. Check to see if the settings work

  1. Open your Windows Command Prompt.
  2. Type java -version in the command line.
  3. If everything was set correctly we’ll see the running version of your installed Java JDK.

As an example on my Windows Command Prompt I have something like:

D:\>java -version
java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)
Java HotSpot(TM) 64-Bit Server VM (build 17+35-LTS-2724, mixed mode, sharing)

If you don’t see the correct output, for instance you get an error like “‘java’ is not recognized as an internal or external command, operable program or batch file.”, please retry the steps described above. Enjoy your new adventure with Java programming. Happy coding!

How to use underscore in numeric literals?

Writing a long sequence of numbers in a code is a hard stuff to read. In the new feature introduced by JDK 7 we are now allowed to write numeric literals using the underscore character to break the numbers to make it easier to read.

You can see how to use underscore in numeric literals in the following examples. And you’ll see it for yourself that it really makes numbers easier to read.

package org.kodejava.basic;

public class UnderscoreNumericExample {
    public static void main(String[] args) {
        // Write numeric literals using underscore as an easier way
        // to read long numbers.
        int maxInt = 2_147_483_647;
        int minInt = -2_147_483_648;

        if (maxInt == Integer.MAX_VALUE) {
            System.out.println("maxInt = " + maxInt);
        }

        if (minInt == Integer.MIN_VALUE) {
            System.out.println("minInt = " + minInt);
        }

        // Write numbers in binary or hex literals using the
        // underscores.
        int maxIntBinary = 0B111_1111_1111_1111_1111_1111_1111_1111;
        int maxIntHex = 0X7____F____F____F____F____F____F____F;

        System.out.println("maxIntBinary = " + maxIntBinary);
        System.out.println("maxIntHex    = " + maxIntHex);
    }
}

The results of the code snippet:

maxInt = 2147483647
minInt = -2147483648
maxIntBinary = 2147483647
maxIntHex    = 2147483647