How do I get the number of processors available to the JVM?

The Runtime.getRuntime().availableProcessors() method returns the maximum number of processors available to the Java virtual machine, the value will never be smaller than one. Knowing the number of available processor you can use it for example to limit the number of thread in your application when you are writing a multi-thread code.

package org.kodejava.lang;

public class NumberProcessorExample {
    public static void main(String[] args) {
        final int processors = Runtime.getRuntime().availableProcessors();
        System.out.println("Number of processors = " + processors);
    }
}

Running the code snippet give you something like:

Number of processors = 8

How do I find Java version?

The simplest way to get the Java version is by running the java -version command in your terminal application or Windows command prompt. If Java is installed and available on your path you can get information like below.

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)

Using System Properties

But if you want to get Java version from your Java class or application you can obtain the Java version by calling the System.getProperty() method and provide the property key as argument. Here are some property keys that related to Java version that you can read from the system properties.

package org.kodejava.lang;

public class JavaVersion {
    public static void main(String[] args) {
        String version = System.getProperty("java.version");
        String versionDate = System.getProperty("java.version.date");
        String runtimeVersion = System.getProperty("java.runtime.version");
        String vmVersion = System.getProperty("java.vm.version");
        String classVersion = System.getProperty("java.class.version");
        String specificationVersion = System.getProperty("java.specification.version");
        String vmSpecificationVersion = System.getProperty("java.vm.specification.version");

        System.out.println("java.version: " + version);
        System.out.println("java.version.date: " + versionDate);
        System.out.println("java.runtime.version: " + runtimeVersion);
        System.out.println("java.vm.version: " + vmVersion);
        System.out.println("java.class.version: " + classVersion);
        System.out.println("java.specification.version: " + specificationVersion);
        System.out.println("java.vm.specification.version: " + vmSpecificationVersion);
    }
}

Running the code above give you output like the following:

java.version: 17
java.version.date: 2021-09-14
java.runtime.version: 17+35-LTS-2724
java.vm.version: 17+35-LTS-2724
java.class.version: 61.0
java.specification.version: 17
java.vm.specification.version: 17

Using Runtime.version()

Since JDK 9 we can use Runtime.version() to get Java runtime version. The feature(), interim(), update and patch() methods of the Runtime.Version class are added in JDK 10. These methods is a replacement for the major(), minor() and security() methods of JDK 9.

Below is the code snippet that demonstrate the Runtime.version().

package org.kodejava.lang;

public class RuntimeVersion {
    public static void main(String[] args) {
        System.out.println("Version: " + Runtime.version());
        System.out.println("Feature: " + Runtime.version().feature());
        System.out.println("Interim: " + Runtime.version().interim());
        System.out.println("Update: " + Runtime.version().update());
        System.out.println("Patch: " + Runtime.version().patch());
        System.out.println("Pre: " + Runtime.version().pre().orElse(""));
        System.out.println("Build: " + Runtime.version().build().orElse(null));
        System.out.println("Optional: " + Runtime.version().optional().orElse(""));
    }
}

Running the code snippet above produce the following output:

Version: 17+35-LTS-2724
Feature: 17
Interim: 0
Update: 0
Patch: 0
Pre: 
Build: 35
Optional: LTS-2724

Here are the summary of outputs running the above code using some JDKs installed on my machine.

Version Feature Interim Update Patch Pre Build Optional
10.0.2+13 10 0 2 0 13
11.0.6+8-LTS 11 0 6 0 8 LTS
12.0.2+10 12 0 2 0 10
13.0.2+8 13 0 2 0 8
14+36-1461 14 0 0 0 36 1461
15.0.2+7-27 15 0 2 0 7 27
17+35-LTS-2724 17 0 0 0 35 LTS-2724

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%.

How to split a string by a number of characters?

The following code snippet will show you how to split a string by numbers of characters. We create a method called splitToNChars() that takes two arguments. The first arguments is the string to be split and the second arguments is the split size.

This splitToNChars() method will split the string in a for loop. First we’ll create a List object that will store parts of the split string. Next we do a loop and get the substring for the defined size from the text and store it into the List. After the entire string is read we convert the List object into an array of String by using the List‘s toArray() method.

Let’s see the code snippet below:

package org.kodejava.lang;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SplitStringForEveryNChar {
    public static void main(String[] args) {
        String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        System.out.println(Arrays.toString(splitToNChar(text, 3)));
        System.out.println(Arrays.toString(splitToNChar(text, 4)));
        System.out.println(Arrays.toString(splitToNChar(text, 5)));
    }

    /**
     * Split text into n number of characters.
     *
     * @param text the text to be split.
     * @param size the split size.
     * @return an array of the split text.
     */
    private static String[] splitToNChar(String text, int size) {
        List<String> parts = new ArrayList<>();

        int length = text.length();
        for (int i = 0; i < length; i += size) {
            parts.add(text.substring(i, Math.min(length, i + size)));
        }
        return parts.toArray(new String[0]);
    }
}

When run the code snippet will output:

[ABC, DEF, GHI, JKL, MNO, PQR, STU, VWX, YZ]
[ABCD, EFGH, IJKL, MNOP, QRST, UVWX, YZ]
[ABCDE, FGHIJ, KLMNO, PQRST, UVWXY, Z]

How do I split a string with multiple spaces?

This code snippet show you how to split string with multiple white-space characters. To split the string this way we use the "\s+" regular expression. The white-space characters include space, tab, line-feed, carriage-return, new line, form-feed.

Let’s see the code snippet below:

package org.kodejava.lang;

import java.util.Arrays;

public class SplitStringMultiSpaces {
    public static void main(String[] args) {
        String text = "04/11/2021    SHOES      RUNNING RED   99.9 USD";

        // Split the string using the \s+ regex to split multi spaces
        // line of text.
        String[] items = text.split("\\s+");
        System.out.println("Length = " + items.length);
        System.out.println("Items  = " + Arrays.toString(items));
    }
}

The result of the code snippet is:

Length = 6
Items  = [04/11/2021, SHOES, RUNNING, RED, 99.9, USD]

How do I create array of unique values from another array?

This code snippet show you how to create an array of unique numbers from another array of numbers.

package org.kodejava.lang;

import java.util.Arrays;

public class UniqueArray {
    /**
     * Return true if num appeared only once in the array.
     */
    public static boolean isUnique(int[] numbers, int num) {
        for (int number : numbers) {
            if (number == num) {
                return false;
            }
        }
        return true;
    }

    /**
     * Convert the given array to an array with unique values and
     * returns it.
     */
    public static int[] toUniqueArray(int[] numbers) {
        int[] temp = new int[numbers.length];
        // in case you have value of 0 in the array
        Arrays.fill(temp, -1);

        int counter = 0;
        for (int number : numbers) {
            if (isUnique(temp, number))
                temp[counter++] = number;
        }

        int[] uniqueArray = new int[counter];
        System.arraycopy(temp, 0, uniqueArray, 0, uniqueArray.length);
        return uniqueArray;
    }

    /**
     * Print given array
     */
    public static void printArray(int[] numbers) {
        for (int number : numbers) {
            System.out.print(number + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 4, 1, 4, 7, 9, 7};
        printArray(numbers);
        printArray(toUniqueArray(numbers));
    }
}

For other example to create unique array check the following example How do I remove duplicate element from array?.