Using Scanner in Java to read input from user until Integer is found

This is an example of getting user input and looping as long as the input is not an integer.
This is done by using the Scanner class and sending as parameter to the constructor. Then we declare a boolean and use that in the while loop to continue the loop as long as the loop is equal to true.
We call the next() method of the Scanner instance which will wait until user types something and hit the enter key. The we use Integer.parseInt on the input value. The code is put in a try-block which has a corresponding catch-block. If the input is not an integer value a NumberFormatException will be thrown, and caught in the catch-block, and the loop will continue to print out a message for the user to enter a value.
If the input is an integer value no exception will be thrown and the boolean flag (keepLooping) will be set to false and the loop will exit.

Possible output from the code above:

Is nullcheck needed before using instanceof?

A question that I have come across every now and then is if it’s necessary to check if a variable is null (or not null) before calling instanceof operator, or calling the isInstance() method of a Class to avoid NullPointerException.

No, that is not necessary. The code below shows an example calling instanceof with both a non-null String and a null String.

The output from the code is:

Remove any whitespace from start and end of a String in Java

This example shows how to remove any whitespace from the beginning and end of a String. This can be done with standard Java using the trim() method of the String class, but we’ll also show how to do it with the StringUtils class of the Apache Commons Lang library, since it is null-safe which means that even if you pass in a null value to them it won’t throw a NullPointerException but rather just return null. The standard Java way of doing this is not null-safe and will throw a NullPointerException if the parameter to the method is null.

Using the StringUtils class it is actually possible to use two methods. The strip() method is the one that should be used since it targets whitespace. The trim() method removes any control character with a value <= 32, but that includes whitespace also. We add an exclamation mark at the end of the values to be sure there are now whitespaces left.

Output from the code above:

The strip() method of StringUtils also have an overloaded method that takes two arguments, the string to be stripped and another string containing the characters that should be stripped from start and end:

Output from the code above is this. Note that only the trailing 'c' is removed, not the center one:

Both trim() and strip() methods of the StringUtils class have a method that returns an empty string if the argument passed to it is null (instead of returning null). The difference is shown below:


How to join values and include prefix and suffix with StringJoiner in Java

StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
In this example we use values and want to join them into one String value separated with comma. We also want to include a prefix and a suffix in that String in form of brackets:

The output from the above code will be:

Now, since the add method of StringJoiner returns itself, a more fluent way of writing would be:

How to create a comma separated string using StringJoiner in Java

This small example shows how to create a comma separated value using the StringJoiner class. The StringJoiner class takes a delimiter as parameter to its constructor which is appended after each value that is added (except for the last one). Finally we use the toString method to print out the value, like this:

The output from the above will look like this:

How to remove last character of a StringBuilder in Java

This example shows how to remove last character of a StringBuilder. There are several ways of doing this but here two possible ways are shown.
The first example uses the method setLength of the StringBuilder to truncate the length by one:

Since the letter ‘g’ is removed from the StringBuilder the output from the code above will be:

Another way of removing last character from a StringBuilder is to use the method deleteCharAt with the last position index as parameter. Like this:

The output from the last example is of course the same as above.

How to generate a UUID or GUID in Java

This example shows how to generate a UUID (Universally Unique Identifier) or as it is sometimes called a GUID (Globally Unique Identifier).
The UUID class has a static factory method to retrieve a type 4 (pseudo randomly generated) UUID.
The UUID value returned from the factory method is immutable and generated using a cryptographically strong pseudo random number generator.

There exists different variations of these identifiers, and the one handled by the methods of the UUID class is a so-called Leach-Salz variant, but the UUID class has constructors to create any type of UUID.

There are four different basic types of UUIDs: time-based, DCE, security, name-based, and randomly generated UUIDs.
These types have a version value of 1, 2, 3 and 4, respectively.

The output from the code above is:

Breaking out of nested loops in Java

If you have a nested loop in java and need to terminate it you can put a label on the other loop to use on the break statement. Without the label, it will break out of the inner loop but will continue in the outer (and enter inner again). The example below shows how this is done:

The output from the code above is this:

Calling constructors from other constructors in the same class in Java

Is it possible to call a constructor from another constructor in the same class?

Yes it is possible using the keyword this, but the call to another constructor must be the very first call that is made in the current constructor, otherwise the compiler will complain.

Nested calls to constructors can be made as we will see further below.

This example below shows how this might look like when calling only one other constructor:

As mentioned above, the call to the other constructor must be the first call in the current constructor. The following would thus fail and will not even compile:

The last example shows how to call several nested constructors:

The output from the last example is:

A wombat is commonly found in Australia and it likes to eat grass

The return statement

The return statement is used to return from a method. A method can have either a return value of some type, or it can have a return type of void (which means it returns nothing).

If we want to return from a method that actually should return a value, the value is specified right after the return statement. The data type of the return value must match the data type in the declaration of the method.

Continue reading