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.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 used to format negative number.

Next we create an instance of DecimalFormat by calling getInstance() method. We apply 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.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.util.support;

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.util;

import org.kodejava.util.support.Student;

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

How can I insert an element in array at a given position?

As we know an array in Java is a fixed-size object, once it created its size cannot be changed. So if you want to have a resizable array-like object where you can insert an element at a given position you can use a java.util.List object type instead.

This example will show you how you can achieve array insert using the java.util.List and java.util.ArrayList object. Let see the code snippet below.

package org.kodejava.util;

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

public class ArrayInsert {
    public static void main(String[] args) {
        // Creates an array of integer value and prints the original values.
        Integer[] numbers = new Integer[]{1, 1, 2, 3, 8, 13, 21};
        System.out.println("Original numbers: " +
                Arrays.toString(numbers));

        // Creates an ArrayList object and initialize its values with the entire
        // content of numbers array. We use the add(index, element) method to add
        // element = 5 at index = 4.
        List<Integer> list = new ArrayList<>(Arrays.asList(numbers));
        list.add(4, 5);

        // Converts back the list into array object and prints the new values.
        numbers = list.toArray(new Integer[0]);
        System.out.println("After insert    : " + Arrays.toString(numbers));
    }
}

In the code snippet above the original array of Integer numbers will be converted into a List, in this case we use an ArrayList, we initialized the ArrayList by passing all elements of the array into the list constructor. The Arrays.asList() can be used to convert an array into a collection type object.

Next we insert a new element into the List using the add(int index, E element) method. Where index is the insert / add position and element is the element to be inserted. After the new element inserted we convert the List back to the original array.

Below is the result of the code snippet above:

Original numbers: [1, 1, 2, 3, 8, 13, 21]
After insert    : [1, 1, 2, 3, 5, 8, 13, 21]

How do I read last n characters from a file?

In the following post you will learn how to read last n characters from a file. The JDK 7 introduces a new SeekableByteChannel interface which allows its implementation to change the position and the size of the byte channel. One of its implementation is the FileChannel class (java.nio.channels.FileChannel).

The FileChannel class make it possible to get hold the current position of where we are going to read from or write to a file. The code snippet below shows you how you can read the last 1000 characters from a log file.

package org.kodejava.io;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileReadLastNCharacters {
    public static void main(String[] args) {
        // Defines the path to the log file and creates a ByteBuffer.
        Path logPath = Paths.get("C:/tools/apache-tomcat-10.0.11/logs/catalina.out");
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        try {
            // Creates FileChannel and open the file channel for read access.
            FileChannel channel = FileChannel.open(logPath, StandardOpenOption.READ);

            // Read a sequence of bytes from the channel into the buffer starting
            // at given file position, which is the channel size - 1000. Because
            // we are going to read the last 1000 characters from the file.
            channel.read(buffer, channel.size() - 1000);
            System.out.println("Characters = " + new String(buffer.array()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The steps in the code snippet above are:

  • Get the path to the log file.
  • Create a ByteBuffer, a buffer where the read bytes to be transferred.
  • Using the FileChannel.open() method we open a file to be read and return a FileChannel object.
  • The read() method of the FileChannel reads a sequence of bytes from the channel and transfer them to the given buffer starting and the position defined by channel.size() - 1000. This method returns the number of bytes read, possible zero, or -1 if the given position is greater than or equal to the file’s current size.
  • Print out the buffered string.