## 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 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).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, data,
ChronoUnit.YEARS.between((LocalDate) data, 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 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)
``````

## 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)
``````

## How do I load file from resource directory?

In the following code snippet we will learn how to load files from resource directory or folder. Resource files can be in a form of image, audio, text, etc. Text resource file for example can be use 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 {
Properties properties = new Properties();

// Load resource relatively to the LoadResourceFile package.
// This actually load resource from
// "/org/kodejava/example/lang/database.conf".
URL resource = getClass().getResource("database.conf");
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");
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 {
Properties properties = new Properties();

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

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

Below is the main program that calls the methods above.

``````package org.kodejava.example.lang;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

public class LoadResourceFile {
public static void main(String[] args) throws Exception {
}
}
``````

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

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

``````jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
``````

`/resources/database.conf`

``````jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/kodejava
``````

The result of this code snippet are:

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

JDBC URL: jdbc:mysql://localhost/kodejava
JDBC URL: jdbc:mysql://localhost/kodejava
``````

## How do I fill array with non-default value?

This code snippet will show you how to create array variable and initialized it with a non-default value. By default, when we create an array of something in Java all entries will have its default value. For primitive types like `int`, `long`, `float` the default value are zero (`0` or `0.0`). For reference types (anything that holds an object in it) will have `null` as the default value. For boolean variable it will be `false`.

If you want to initialize the array to different value you can use the `Arrays.fill()` method. This method will help you to set the value for every elements of the array.

Let see the following code snippet as an example:

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

import java.util.Arrays;

public class ArraysFillExample {
public static void main(String[] args) {
// Assign -1 to each elements of numbers array
int[] numbers = new int;
Arrays.fill(numbers, -1);
System.out.println("Numbers: " + Arrays.toString(numbers));

// Assign 1.0f to each elements of prices array
float[] prices = new float;
Arrays.fill(prices, 1.0f);
System.out.println("Prices : " + Arrays.toString(prices));

// Assign empty string to each elements of words array
String[] words = new String;
Arrays.fill(words, "");
System.out.println("Words  : " + Arrays.toString(words));

// Assign 9 to each elements of the multi array
int[][] multi = new int;
for (int[] array : multi) {
Arrays.fill(array, 9);
}
System.out.println("Multi  : " + Arrays.deepToString(multi));
}
}
``````

In the code snippet above we utilize the `Arrays.fill()` utility method to assign value for each elements of the `int`, `float` and `String` array. To change the default value of multi dimensional array we can’t directly call the `Arrays.fill()` method. In the example we use for-loop to set each elements of the sub-array using the `Arrays.fill()` method.

The output of the code snippet above are:

``````Numbers: [-1, -1, -1, -1, -1]
Prices : [1.0, 1.0, 1.0, 1.0, 1.0]
Words  : [, , , , ]
Multi  : [[9, 9, 9], [9, 9, 9], [9, 9, 9]]
``````

## 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.example.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 do I parse negative number in parentheses?

In financial application negative numbers are often represented in parentheses. In this post we will learn how we can parse or convert the negative number in parentheses to produce the represented number value. To parse text / string to a number we can use the `java.text.DecimalFormat` class.

Beside number in parentheses, in this example we also parse negative number that use the minus sign with the currency symbol like `\$`. Let’s jump to the code snippet below:

``````package org.kodejava.example.text;

import java.text.DecimalFormat;

public class NegativeNumberParse {
// Pattern for parsing negative number.
public static final String PATTERN1 = "#,##0.00;(#,##0.00)";
public static final String PATTERN2 = "\$#,##0.00;-\$#,##0.00";

public static void main(String[] args) throws Exception {
DecimalFormat df = new DecimalFormat(PATTERN1);

String number1 = "(1000)";
String number2 = "(1,500.99)";

System.out.println("number1 = " + df.parse(number1));
System.out.println("number2 = " + df.parse(number2));

df = (DecimalFormat) DecimalFormat.getInstance();
df.applyPattern(PATTERN2);

String number3 = "-\$1000";
String number4 = "-\$1,500.99";

System.out.println("number3 = " + df.parse(number3));
System.out.println("number4 = " + df.parse(number4));
}
}
``````

And here are the results of our code snippet above:

``````number1 = -1000
number2 = -1500.99
number3 = -1000
number4 = -1500.99
``````

If you need to display or format negative numbers in parentheses you can take a look at the following example How do I display negative number in parentheses?.

## How do I display negative number in parentheses?

The code snippet below show us how to display or format negative number in parentheses. We start by defining the number format, the pattern has two parts separated by a semicolon. In the snippet we use the `#,##0.00;(#,##0.00)` pattern. The pattern after the semicolon will be use to format negative number.

Next we create an instance of `DecimalFormat` by calling `getInstance()` method. We apply the the format pattern for the formatter object by calling the `applyPattern()` method of the `DecimalFormat` instance. To format the number we simply call the `format()` method and pass the number we are going to format for display or print out.

``````package org.kodejava.example.text;

import java.text.DecimalFormat;

public class NegativeNumberFormat {
// Pattern for formatting negative number.
public static final String PATTERN1 = "#,##0.00;(#,##0.00)";
public static final String PATTERN2 = "\$#,##0.00;-\$#,##0.00";

public static void main(String[] args) {
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
df.applyPattern(PATTERN1);

// Format using parentheses
System.out.println("Positive: " + df.format(125));
System.out.println("Negative: " + df.format(-125));

// Format using currency symbol and minus sign
df.applyPattern(PATTERN2);
System.out.println("Positive: " + df.format(1000));
System.out.println("Negative: " + df.format(-1000));
}
}
``````

The result of the code snippet above is:

``````Positive: 125.00
Negative: (125.00)
Positive: \$1,000.00
Negative: -\$1,000.00
``````

If you need to parse negative numbers in parentheses to produce the represented number you can see the following example How do I parse negative number in parentheses?.

## How do I implement equals() and hashCode() method using java.util.Objects?

This example will show you how to implement the `equals()` and `hashCode()` object using `java.util.Objects` class. The `Objects` class provides a set of utility methods to work with object such as comparing two objects for equality and calculating the hashcode. Other methods include object null check methods, object to string method, etc.

To demonstrate `equals()` and `hash()` methods we’ll create a simple POJO called `Student` with a couple of properties such as `id`, `name` and `dateOfBirth`.

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

import java.time.LocalDate;
import java.util.Objects;

public class Student {
private Long id;
private String name;
private LocalDate dateOfBirth;

public Student() {
}

public Student(Long id, String name, LocalDate dateOfBirth) {
this.id = id;
this.name = name;
this.dateOfBirth = dateOfBirth;
}

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public LocalDate getDateOfBirth() {
return dateOfBirth;
}

public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

Student that = (Student) o;
return Objects.equals(this.id, that.id)
&& Objects.equals(this.name, that.name)
&& Objects.equals(this.dateOfBirth, that.dateOfBirth);
}

@Override
public int hashCode() {
return Objects.hash(id, name, dateOfBirth);
}
}
``````

Using the `Objects.equals()` and `Objects.hash()` methods in the `Student` class makes the implementation of the `equals()` method and the `hashCode()` method concise, easy to read and to understand. The `Objects` utility class will operate in a null-safe way which means that it will check for a null fields of the object.

The code snippet below will demonstrate the use of `Student` class. Which will compare objects using the `equals()` method and print out the calculated hashcode of the object.

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

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

public class EqualsHashCodeExample {
public static void main(String[] args) {
Student student1 = new Student(1L, "Alice", LocalDate.of(1990, Month.APRIL, 1));
Student student2 = new Student(1L, "Alice", LocalDate.of(1990, Month.APRIL, 1));
Student student3 = new Student(2L, "Bob", LocalDate.of(1992, Month.DECEMBER, 21));

System.out.println("student1.equals(student2) = " + student1.equals(student2));
System.out.println("student1.equals(student3) = " + student1.equals(student3));
System.out.println("student1.hashCode() = " + student1.hashCode());
System.out.println("student2.hashCode() = " + student2.hashCode());
System.out.println("student3.hashCode() = " + student3.hashCode());
}
}
``````

And here are the result of the code snippet above:

``````student1.equals(student2) = true
student1.equals(student3) = false
student1.hashCode() = 1967967937
student2.hashCode() = 1967967937
student3.hashCode() = 6188033
``````

Another approach for implementing the `equals()` and `hashCode()` method is using the Apache Commons Lang library. And example of it can be seen here: How to implement the hashCode and equals method using Apache Commons?.