How do I terminate a Java application?

In an application we sometimes want to terminate the execution of our application, for instance because it cannot find the required resource.

To terminate it we can use exit(status) method in java.lang.System class or in the java.lang.Runtime class. When terminating an application we need to provide a status code, a non-zero status assigned for any abnormal termination.

package org.kodejava.lang;

import java.io.File;

public class AppTerminate {
    public static void main(String[] args) {
        File file = new File("config.xml");

        int errCode = 0;
        if (!file.exists()) {
            errCode = 1;
        }

        // When the error code is not zero go terminate
        if (errCode > 0) {
            System.exit(errCode);
        }
    }
}

The call to System.exit(status) is equals to Runtime.getRuntime().exit(status). Actually the System class will delegate the termination process to the Runtime class.

Running the code give the following output because it can’t find the config.xml file.

Process finished with exit code 1

How do I check if a string is a valid number?

When building a computer program we will use a lot of string to represent our data. The data might not just information about our customer name, email or address, but will also contain numeric data represented as string. So how do we know if this string contains a valid number?

Java provides some wrappers to the primitive data types that can be used to do the checking. These wrappers come with the parseXXX() method such as Integer.parseInt(), Float.parseFloat() and Double.parseDouble() methods.

package org.kodejava.lang;

public class NumericParsingExample {
    public static void main(String[] args) {
        String age = "15";
        String height = "160.5";
        String weight = "55.9";

        try {
            int theAge = Integer.parseInt(age);
            float theHeight = Float.parseFloat(height);
            double theWeight = Double.parseDouble(weight);

            System.out.println("Age    = " + theAge);
            System.out.println("Height = " + theHeight);
            System.out.println("Weight = " + theWeight);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

In the example code we use Integer.parseInt(), Float.parseFloat(), Double.parseDouble() methods to check the validity of our numeric data. If the string is not a valid number java.lang.NumberFormatException will be thrown.

The result of our example:

Age    = 15
Height = 160.5
Weight = 55.9

How do I get the minimum and maximum value of a primitive data types?

To get the minimum or maximum value of a primitive data types such as byte, short, int, long, float and double we can use the wrapper class provided for each of them, the wrapper classes are Byte, Short, Integer, Long, Float and Double which is located in java.lang package.

package org.kodejava.lang;

public class MinMaxExample {
    public static void main(String[] args) {
        System.out.println("Byte.MIN    = " + Byte.MIN_VALUE);
        System.out.println("Byte.MAX    = " + Byte.MAX_VALUE);
        System.out.println("Short.MIN   = " + Short.MIN_VALUE);
        System.out.println("Short.MAX   = " + Short.MAX_VALUE);
        System.out.println("Integer.MIN = " + Integer.MIN_VALUE);
        System.out.println("Integer.MAX = " + Integer.MAX_VALUE);
        System.out.println("Long.MIN    = " + Long.MIN_VALUE);
        System.out.println("Long.MAX    = " + Long.MAX_VALUE);
        System.out.println("Float.MIN   = " + Float.MIN_VALUE);
        System.out.println("Float.MAX   = " + Float.MAX_VALUE);
        System.out.println("Double.MIN  = " + Double.MIN_VALUE);
        System.out.println("Double.MAX  = " + Double.MAX_VALUE);
    }
}

The result of the code above shows the minimum and maximum value for each data types.

Byte.MIN    = -128
Byte.MAX    = 127
Short.MIN   = -32768
Short.MAX   = 32767
Integer.MIN = -2147483648
Integer.MAX = 2147483647
Long.MIN    = -9223372036854775808
Long.MAX    = 9223372036854775807
Float.MIN   = 1.4E-45
Float.MAX   = 3.4028235E38
Double.MIN  = 4.9E-324
Double.MAX  = 1.7976931348623157E308

How do I convert primitive data types into String?

There are times when we want to convert data from primitive data types into a string, for instance when we want to format output on the screen or simply mixing it with other string. Using a various static method String.valueOf() we can get a string value of them.

Here is the code sample:

package org.kodejava.lang;

public class StringValueOfExample {
    public static void main(String[] args) {
        boolean b = false;
        char c = 'c';
        int i = 100;
        long l = 100000;
        float f = 3.4f;
        double d = 500.99;

        String u = String.valueOf(b);
        String v = String.valueOf(c);
        String w = String.valueOf(i);
        String x = String.valueOf(l);
        String y = String.valueOf(f);
        String z = String.valueOf(d);
    }
}

When called with boolean argument the String.valueOf() method return true or false string depending on the boolean argument value. When called with char argument, a 1 length sized string returned.

For int, long, float, double the results are the same as calling Integer.toString(), Long.toString(), Float.toString() and Double.toString() respectively.

How do I check a string starts with a specific word?

To test if a string starts with a specific prefix we can use the String.startsWith(String prefix) method. This method returns a boolean true as the result if the string starts with that specified prefix. The String.startsWith() method checks the prefix in case-sensitive manner.

The following code snippet give us a small example how to use this method, but instead of just straightly checks using the startsWith() method, we add a scanner that allows us to input the prefix that we want to test.

package org.kodejava.lang;

import java.util.Scanner;

import static java.lang.System.in;

public class StringStartsWithExample {
    private static final Scanner scanner = new Scanner(in);

    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        System.out.println("Text: " + text);

        System.out.print("Type the prefix to test: ");
        String search = scanner.nextLine();

        // Check if the text start with the search text.
        if (text.startsWith(search)) {
            System.out.println("Yes, the fox is the quick one");
        } else {
            System.out.println("The fox is a slow fox");
        }
    }
}

The code snippet print the following output:

Text: The quick brown fox jumps over the lazy dog
Type the prefix to test: The quick brown fox
Yes, the fox is the quick one