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);
}

How do I convert number into Roman Numerals?

You want to convert numbers into their Roman numerals representation and vice versa. The solution here is to tackle the problem as a unary problem where the Roman numerals represented as a single element, the “I” character. We start by representing the number as a repeated sequence of the “I” characters. And then replace the characters according to next bigger symbol in roman numeral.

To convert from the Roman numerals to numbers we reverse the process. By the end of the process we will get a sequence of repeated “I” characters. The length of the final string returned by this process is the result of the roman numeral conversion to number.

In the code snippet below we create two methods. The toRoman(int number) method for converting number to roman numerals and the toNumber(String roman) method for converting from roman numerals to number. Both of this method utilize the String.replace() method for calculating the conversion result.

Let’s see the code in action.

package org.kodejava.lang;

public class RomanNumber {
    public static void main(String[] args) {
        for (int n = 1; n <= 4999; n++) {
            String roman = RomanNumber.toRoman(n);
            int number = RomanNumber.toNumber(roman);

            System.out.println(number + " = " + roman);
        }
    }

    private static String toRoman(int number) {
        return String.valueOf(new char[number]).replace('\0', 'I')
                .replace("IIIII", "V")
                .replace("IIII", "IV")
                .replace("VV", "X")
                .replace("VIV", "IX")
                .replace("XXXXX", "L")
                .replace("XXXX", "XL")
                .replace("LL", "C")
                .replace("LXL", "XC")
                .replace("CCCCC", "D")
                .replace("CCCC", "CD")
                .replace("DD", "M")
                .replace("DCD", "CM");
    }

    private static Integer toNumber(String roman) {
        return roman.replace("CM", "DCD")
                .replace("M", "DD")
                .replace("CD", "CCCC")
                .replace("D", "CCCCC")
                .replace("XC", "LXL")
                .replace("C", "LL")
                .replace("XL", "XXXX")
                .replace("L", "XXXXX")
                .replace("IX", "VIV")
                .replace("X", "VV")
                .replace("IV", "IIII")
                .replace("V", "IIIII").length();
    }
}

The 10 randoms result of the conversion listed below:

18 = XVIII
208 = CCVIII
843 = DCCCXLIII
1995 = MCMXCV
2000 = MM
2017 = MMXVII
2562 = MMDLXII
3276 = MMMCCLXXVI
4067 = MMMMLXVII
4994 = MMMMCMXCIV

How do I align string print out in left, right, center alignment?

The following code snippet will teach you how to align string in left, right or center alignment when you want to print out string to a console. We will print the string using the printf(String format, Object... args) method. The format specifier / parameter defines how the string will be formatted for output and the args is the value that will be formatted.

The format parameter / specifier include flags, width, precision and conversion-characters in the order shown below. The square brackets in the notation means the part is an optional parameter.

% [flags] [width] [.precision] conversion-character
Flags Description
- left-align the output, when not specified the default is to right-align
+ print (+) or (-) sign for numeric value
0 zero padded a numeric value
, comma grouping separator for number greater that 1000
space will output a (-) symbol for negative value and a space if positive
Conversion Description
s string, use capital S to uppercase the strings
c character, use capital C to uppercase the characters
d integer: byte, short, integer, long
f floating point number: float, double
n new line

Width: Defines the field width for printing out the value of argument. It also represents the minimum number of characters to
be printed out to the output.

Precision: For floating-point conversion the precision define the number of digits of precision in a floating point value. For string value this will extract the substring.

To center the string for output we use the StringUtils.center() method from the Apache Commons Lang library. This method will center-align the string str in a larger string of size using the default space character (‘ ‘). You can supply the third parameter to define your own space character / string.

package org.kodejava.lang;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class StringAlignment {
    private static final Object[][] people = {
            {"Alice", LocalDate.of(2000, Month.JANUARY, 1)},
            {"Bob", LocalDate.of(1989, Month.DECEMBER, 15)},
            {"Carol", LocalDate.of(1992, Month.JULY, 24)},
            {"Ted", LocalDate.of(2006, Month.MARCH, 13)},
    };

    public static void main(String[] args) {
        String nameFormat = "| %1$-20s | ";
        String dateFormat = " %2$tb %2$td, %2$tY  | ";
        String ageFormat = " %3$3s |%n";
        String format = nameFormat.concat(dateFormat).concat(ageFormat);
        String line = new String(new char[48]).replace('\0', '-');

        System.out.println(line);
        System.out.printf("|%s|%s|%s|%n",
                StringUtils.center("Name", 22),
                StringUtils.center("Birth Date", 16),
                StringUtils.center("Age", 6));
        System.out.println(line);

        for (Object[] data : people) {
            System.out.printf(format,
                    data[0], data[1],
                    ChronoUnit.YEARS.between((LocalDate) data[1], LocalDate.now()));
        }

        System.out.println(line);
    }
}

Here is the output of our code snippet above:

------------------------------------------------
|         Name         |   Birth Date   | Age  |
------------------------------------------------
| Alice                |  Jan 01, 2000  |   17 |
| Bob                  |  Dec 15, 1989  |   27 |
| Carol                |  Jul 24, 1992  |   24 |
| Ted                  |  Mar 13, 2006  |   10 |
------------------------------------------------

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Maven Central

How do I load file from resource directory?

In the following code snippet we will learn how to load files from resource directory. Resource files can be in a form of image, audio, text, etc. Text resource file for example can be used to store application configurations, such as database configuration.

To load this resource file you can use a couple methods utilizing the java.lang.Class methods or the java.lang.ClassLoader methods. Both Class and ClassLoader provides getResource() and getResourceAsStream() methods to load resource file. The first method return a URL object while the second method return an InputStream.

When using the Class method, if the resource name started with “/” that identifies it is an absolute name. Absolute name means that it will load from the specified directory name or package name. While if it is not started with “/” then it is identified as a relative name. This means that it will look in the same package as the class that tries to load the resource.

App.class.getResource("database.conf");

The snippet will attempt to load the resource file from the same package as the App class. If the App class package is org.kodejava then the database.conf file must be located at /org/kodejava/. This is the relative resource name.

App.class.getResource("/org/kodejava/conf/database.conf"):

The snippet will attempt to load the resource file from the given package name. You should place the configuration file under /org/kodejava/conf/ to enable the application to load it. This is the absolute resource name.

Below is a snippet that use the Class method to load resources.

private void loadUsingClassMethod() throws IOException {
    System.out.println("LoadResourceFile.loadUsingClassMethod");
    Properties properties = new Properties();

    // Load resource relatively to the LoadResourceFile package.
    // This actually load resource from
    // "/org/kodejava/lang/database.conf".
    URL resource = getClass().getResource("database.conf");
    properties.load(new FileReader(Objects.requireNonNull(resource).getFile()));
    System.out.println("JDBC Driver: " + properties.get("jdbc.driver"));

    // Load resource using absolute name. This will read resource
    // from the root of the package. This will load "/database.conf".
    InputStream is = getClass().getResourceAsStream("/database.conf");
    properties.load(is);
    System.out.println("JDBC Driver: " + properties.get("jdbc.driver"));
}

When we use the ClassLoader method the resource name should not begins with a “/“. This method will not apply any absolute / relative transformation to the resource name like the Class method. Here a snippet of a method that use the ClassLoader method.

private void loadUsingClassLoaderMethod() throws IOException {
    System.out.println("LoadResourceFile.loadUsingClassLoaderMethod");
    Properties properties = new Properties();

    // When using the ClassLoader method, the resource name should
    // not be started with "/". This method will not apply any
    // absolute/relative transformation to the resource name.
    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource("database.conf");
    properties.load(new FileReader(Objects.requireNonNull(resource).getFile()));
    System.out.println("JDBC URL: " + properties.get("jdbc.url"));

    InputStream is = classLoader.getResourceAsStream("database.conf");
    properties.load(is);
    System.out.println("JDBC URL: " + properties.get("jdbc.url"));
}

Below is the main program that calls the methods above.

package org.kodejava.lang;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

public class LoadResourceFile {
    public static void main(String[] args) throws Exception {
        LoadResourceFile demo = new LoadResourceFile();
        demo.loadUsingClassMethod();
        demo.loadUsingClassLoaderMethod();
    }
}

In the snippet above we load two difference resources. One contains Oracle database configuration and the other is MySQL database configuration.

/resources/org/kodejava/lang/database.conf

jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
jdbc.username=kodejava
jdbc.password=kodejava123

/resources/database.conf

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/kodejava
jdbc.username=kodejava
jdbc.password=kodejava123

The result of this code snippet are:

LoadResourceFile.loadUsingClassMethod
JDBC Driver: oracle.jdbc.driver.OracleDriver
JDBC Driver: com.mysql.jdbc.Driver

LoadResourceFile.loadUsingClassLoaderMethod
JDBC URL: jdbc:mysql://localhost/kodejava
JDBC URL: jdbc:mysql://localhost/kodejava

How do I escape / display percent sign in printf statement?

You have a problem displaying the % sign when you want to print a number in percentage format using the printf() method. Because the % sign is use as a prefix of format specifiers, you need to escape it if you want to display the % sign as part of the output string.

To escape the percent sign (%) you need to write it twice, like %%. It will print out a single % sign as part of your printf() method output. Let see an example in the code snippet below:

package org.kodejava.lang;

public class EscapePercentSignExample {
    public static void main(String[] args) {
        String format = "The current bank interest rate is %6.2f%%.%n";
        System.out.printf(format, 10f);
    }
}

In the code snippet above we use the following format %6.2f%%.%n which can be explained as:

  • %6.2f format the number (10f) as six characters in width, right justified, with two places after decimal point. The f conversion character means it accept a float value.
  • %% will escape the % sign and print it as part of the output.
  • %n will print out a new line character.

When you execute the code, it will print:

The current bank interest rate is  10.00%.