## 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 numerals 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.example.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 send POST request with a JSON body using the HttpClient?

The following code snippet show you how to send POST request with a JSON body using HttpClient. The payload in this example is a user information containing `id`, `first_name` and a `last_name`. We placed the payload in an object called `StringEntity` and also set its content type to `ContentType.APPLICATION_FORM_URLENCODED`.

On the other end called by this post request, data can be read for instance in a Java Servlet using the `HttpServletRequest.getParameter()` method. For example to read the JSON body send below we can call `request.getParameter("data")`. Which will give us the payload send using the HttpClient Post request.

Let’s jump into the code snippet below:

``````package org.kodejava.example.httpclient;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class HttpPostJsonExample {
public static void main(String[] args) throws Exception {
"\"first_name\": \"System\", " +
"}";
ContentType.APPLICATION_FORM_URLENCODED);

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://localhost:8080/register");
request.setEntity(entity);

HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
}
}
``````

Maven Dependencies

``````<!-- http://repo1.maven.org/maven2/org/apache/httpcomponents/httpclient/4.5.3/httpclient-4.5.3.jar -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
``````

## 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.example.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 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

``````<!-- http://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.6/commons-lang3-3.6.jar -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.6</version>
</dependency>
``````

## How do I sort file names by their extension?

To sort file names by their extension we can use the `ExtensionFileComparator` class from the Apache Commons IO library. This class provide a couple instances of comparator such as:

Comparator Description
`EXTENSION_COMPARATOR` Case sensitive extension comparator
`EXTENSION_REVERSE` Reverse case sensitive extension comparator
`EXTENSION_INSENSITIVE_COMPARATOR` Case insensitive extension comparator
`EXTENSION_INSENSITIVE_REVERSE` Reverse case insensitive extension comparator
`EXTENSION_SYSTEM_COMPARATOR` System sensitive extension comparator
`EXTENSION_SYSTEM_REVERSE` Reverse system sensitive path comparator

The following snippet show you how to use the first two comparators listed above.

``````package org.kodejava.example.commons.io;

import org.apache.commons.io.FilenameUtils;
import static org.apache.commons.io.comparator.ExtensionFileComparator.*;

import java.io.File;
import java.util.Arrays;

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

// Excludes directory in the list
File[] files = file.listFiles(File::isFile);

if (files != null) {
// Sort in ascending order.
Arrays.sort(files, EXTENSION_COMPARATOR);
FileSortByExtension.displayFileOrder(files);

// Sort in descending order.
Arrays.sort(files, EXTENSION_REVERSE);
FileSortByExtension.displayFileOrder(files);
}
}

private static void displayFileOrder(File[] files) {
System.out.printf("%-20s | %s%n", "Name", "Ext");
System.out.println("--------------------------------");
for (File file : files) {
System.out.printf("%-20s | %s%n", file.getName(),
FilenameUtils.getExtension(file.getName()));
}
System.out.println("");
}
}
``````

The result of the code snippet:

``````Name                 | Ext
--------------------------------
lipsum.doc           | doc
lipsum.docx          | docx
data.html            | html
contributors.txt     | txt
pom.xml              | xml

Name                 | Ext
--------------------------------
pom.xml              | xml
contributors.txt     | txt
data.html            | html
lipsum.docx          | docx
lipsum.doc           | doc
``````

Maven Dependencies

``````<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
``````

## How do I sort files and directories based on their size?

In this example you will learn how to sort files and directories based on their size. Using the Apache Commons IO we can utilize the `SizeFileComparator` class. This class provides some instances to sort file size such as:

Comparator Description
SIZE_COMPARATOR Size comparator instance – directories are treated as zero size
SIZE_REVERSE Reverse size comparator instance – directories are treated as zero size
SIZE_SUMDIR_COMPARATOR Size comparator instance which sums the size of a directory’s contents
SIZE_SUMDIR_REVERSE Reverse size comparator instance which sums the size of a directory’s contents

``````package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Arrays;

import static org.apache.commons.io.comparator.SizeFileComparator.*;

public class FileSortBySize {
public static void main(String[] args) {
File dir = new File(".");
File[] files = dir.listFiles();

if (files != null) {
// Sort files in ascending order based on file size.
System.out.println("Ascending order.");
Arrays.sort(files, SIZE_COMPARATOR);
FileSortBySize.displayFileOrder(files, false);

// Sort files in descending order based on file size
System.out.println("Descending order.");
Arrays.sort(files, SIZE_REVERSE);
FileSortBySize.displayFileOrder(files, false);

// Sort files in ascending order based on file / directory
// size
System.out.println("Ascending order with directories.");
Arrays.sort(files, SIZE_SUMDIR_COMPARATOR);
FileSortBySize.displayFileOrder(files, true);

// Sort files in descending order based on file / directory
// size
System.out.println("Descending order with directories.");
Arrays.sort(files, SIZE_SUMDIR_REVERSE);
FileSortBySize.displayFileOrder(files, true);
}
}

private static void displayFileOrder(File[] files, boolean displayDirectory) {
for (File file : files) {
if (!file.isDirectory()) {
System.out.printf("%-25s - %s%n", file.getName(),
FileUtils.byteCountToDisplaySize(file.length()));
} else if (displayDirectory) {
long size = FileUtils.sizeOfDirectory(file);
String friendlySize = FileUtils.byteCountToDisplaySize(size);
System.out.printf("%-25s - %s%n", file.getName(),
friendlySize);
}
}
System.out.println("------------------------------------");
}
}
``````

In the code snippet above we use a couple method from the `FileUtils` class such as the `FileUtils.sizeOfDirectory()` to calculate the size of a directory and `FileUtils.byteCountToDisplaySize()` to create human readable file size.

The result of the code snippet:

``````Ascending order.
.editorconfig             - 389 bytes
kodejava.iml              - 868 bytes
pom.xml                   - 1 KB
------------------------------------
Descending order.
pom.xml                   - 1 KB
kodejava.iml              - 868 bytes
.editorconfig             - 389 bytes
------------------------------------
Ascending order with directories.
.editorconfig             - 389 bytes
src                       - 851 bytes
kodejava.iml              - 868 bytes
pom.xml                   - 1 KB
apache-commons-example    - 8 KB
hibernate-example         - 29 KB
.idea                     - 85 KB
------------------------------------
Descending order with directories.
.idea                     - 85 KB
hibernate-example         - 29 KB
apache-commons-example    - 8 KB
pom.xml                   - 1 KB
kodejava.iml              - 868 bytes
src                       - 851 bytes
.editorconfig             - 389 bytes
``````

Maven Dependencies

``````<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
``````

## How to read text file contents line by line?

In the following code example you will learn how to read file contents line by line using the Apache Commons `FileUtils.lineIterator()` method. Reading file contents one line at a time, do some processing, and release it from memory immediately will lower the memory consumption used by your program.

The snippet below give you the basic usage of the `FileUtils.lineIterator()` method. You pass the file to read and the encoding to use. An `Iterator` of the lines in the file will be returned. Use the `hasNext()` method to see if there are lines to read from the iterator. The `nextLine()` method will give you the next line from the file.

When we finished with the iterator we need to close it using the `LineIterator.close()` or `LineIterator.closeQuietly()` method.

``````package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

import java.io.File;
import java.net.URL;
import java.util.Objects;

public static void main(String[] args) throws Exception {
// Load file from resource directory.
"Resource could not be found.");

File file = new File(url.getFile());
LineIterator iterator = FileUtils.lineIterator(file, "UTF-8");
try {
while (iterator.hasNext()) {
String line = iterator.nextLine();
System.out.println("line = " + line);
}
} finally {
LineIterator.closeQuietly(iterator);
}
}
}
``````

In the example above we load the file from a resource directory. That’s why we use the `ClassLoader.getResource()` method. If you want to load a file from an absolute path you can simply create a `File` object and pass the absolute path to the file.

Maven Dependency

``````<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
``````

## How do I generate random string?

``````package org.kodejava.example.security;

import java.security.SecureRandom;
import java.util.Random;

public class RandomString {
public static final String SOURCES =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";

public static void main(String[] args) {
RandomString rs = new RandomString();
System.out.println(rs.generateString(new Random(), SOURCES, 10));
System.out.println(rs.generateString(new Random(), SOURCES, 10));
System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));
System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));
}

/**
* Generate a random string.
*
* @param random the random number generator.
* @param characters the characters for generating string.
* @param length the length of the generated string.
* @return
*/
public String generateString(Random random, String characters, int length) {
char[] text = new char[length];
for (int i = 0; i < length; i++) {
text[i] = characters.charAt(random.nextInt(characters.length()));
}
return new String(text);
}
}
``````

Example string produced by the code snippets are:

``````uxEUFqTqS0
vr89vdF4gh
ysYF9XEHhO5FtDf
aBANhrLObZ1XLJi
``````

## How to check if an object reference is not null?

Usually, if not always, we use the `if` statement combined with `==` or `!=` operators to check if an object reference is null or not. We do this to validate arguments passed to constructors or methods doesn’t contain a null value. These null check can be seen as clutter in our code.

The solution is to use the `java.util.Objects` class. This static utility class provides methods like `requireNonNull(T)` and `requireNonNull(T, String)` to check if the specified object reference is not null. If null these method will throw a `NullPointerException`. Using the second method variant we can customise the exception message.

The example below shows how we use these methods.

``````package org.kodejava.example.util;

import java.util.Objects;

public class ObjectsNullCheckDemo {
private String firstName;
private String lastName;

/**
* Validate constructor arguments. The firstName and lastName
* arguments can't be null. A NullPointerException with the
* specified message will be thrown.
*/
public ObjectsNullCheckDemo(String firstName, String lastName) {
this.firstName = Objects.requireNonNull(firstName,
"First name can't be null.");
this.lastName = Objects.requireNonNull(lastName,
"Last name can't be null.");
}

public void setFirstName(String firstName) {
// First name can't be null.
this.firstName = Objects.requireNonNull(firstName,
"First name can't be null.");
}

public void setLastName(String lastName) {
// Last name can't be null.
this.lastName = Objects.requireNonNull(lastName,
"Last name can't be null.");
}

public static void main(String[] args) {
// This line is fine.
ObjectsNullCheckDemo demo = new ObjectsNullCheckDemo("John", "Doe");
System.out.println("demo = " + demo);

try {
// This line produce a NullPointerException
ObjectsNullCheckDemo demo1 = new ObjectsNullCheckDemo("Alice", null);
} catch (Exception e) {
e.printStackTrace();
}

String name = null;
try {
// The line below will throw java.lang.NullPointerException.
Objects.requireNonNull(name);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public String toString() {
return "ObjectsNullCheckDemo{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
``````

Running the code above will print the following result:

``````demo = ObjectsNullCheckDemo{firstName='John', lastName='Doe'}
java.lang.NullPointerException: Last name can't be null.
at java.util.Objects.requireNonNull(Objects.java:228)
at org.kodejava.example.util.ObjectsNullCheckDemo.<init>(ObjectsNullCheckDemo.java:14)
at org.kodejava.example.util.ObjectsNullCheckDemo.main(ObjectsNullCheckDemo.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:203)
at org.kodejava.example.util.ObjectsNullCheckDemo.main(ObjectsNullCheckDemo.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
``````

## How do I create a custom TemporalAdjuster?

In this example we are going to learn how to implement a custom `TemporalAdjuster`. We are going to create `TemporalAdjuster` to find the next working day from a specified date. We will use 5 working days, from Monday to Friday.

The custom temporal adjuster class should implement the `TemporalAdjuster` interface, which define a single method that we must implement, the `adjustInto(Temporal)` method.

``````package org.kodejava.example.datetime;

import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;

@Override
int field = temporal.get(ChronoField.DAY_OF_WEEK);
DayOfWeek dayOfWeek = DayOfWeek.of(field);

if (DayOfWeek.FRIDAY.equals(dayOfWeek)) {
} else if (DayOfWeek.SATURDAY.equals(dayOfWeek)) {
}
}
}
``````

The `NextWorkingDayAdjuster` move the temporal object a day forward. Except if it is on Friday or Saturday, which will move the temporal object three days or two days forward respectively. This will make it return Monday as the next working day.

After creating the custom adjuster, now let’s create an example that use the `NextWorkingDayAdjuster` class.

``````package org.kodejava.example.datetime;

import java.time.LocalDate;
import java.time.Month;

public static void main(String[] args) {

LocalDate now = LocalDate.now();
LocalDate nextDay = now.with(nextWorkingDay);
System.out.println("now            = " + now);
System.out.println("nextWorkingDay = " + nextDay);

LocalDate friday = LocalDate.of(2016, Month.MARCH, 11);
nextDay = friday.with(nextWorkingDay);
System.out.println("friday         = " + friday);
System.out.println("nextWorkingDay = " + nextDay);

LocalDate saturday = LocalDate.of(2016, Month.MARCH, 12);
nextDay = saturday.with(nextWorkingDay);
System.out.println("saturday       = " + saturday);
System.out.println("nextWorkingDay = " + nextDay);
}
}
``````

And here are the results of our code:

``````now            = 2016-03-10
nextWorkingDay = 2016-03-11
friday         = 2016-03-11
nextWorkingDay = 2016-03-14
saturday       = 2016-03-12
nextWorkingDay = 2016-03-14
``````

## Using format flags to format negative number in parentheses

In this example we are going to learn to use a `java.util.Formatter` to format negative number in parentheses. The `Formatter` can use a format flags to format a value. To display a negative number in parentheses we can user the `(` flag. This flag display negative number inside parentheses instead of using the `-` symbol.

The following code snippet below will show you how to do it. We start the example by using the `Formatter` object and simplified using the `format()` method of the `String` class.

``````package org.kodejava.example.util;

import java.util.Formatter;
import java.util.Locale;

public class FormatNegativeNumber {
public static void main(String[] args) {
// Creates an instance of Formatter, format the number using the
// format and print out the result.
Formatter formatter = new Formatter();
formatter.format("%(,.2f", -199.99f);
System.out.println("number1 = " + formatter);

// Use String.format() method instead of creating an instance of
// Formatter. Format a negative number using Germany locale.
String number2 = String.format(Locale.GERMANY, "%(,8.2f", -49.99);
System.out.println("number2 = " + number2);

// Format number using Indonesian locale. The thousand separator is "."
// in Indonesian number.
String number3 = String.format(new Locale("id", "ID"), "%(,d", -10000);
System.out.println("number3 = " + number3);
}
}
``````

The result of this code snippet:

``````number1 = (199.99)
number2 =  (49,99)
number3 = (10.000)
``````