Skip to content

Java Core

Using StringBuilder instead of usual concatenation. When is it appropriate?

You might know that using string concatenation in Java is not a good practice as it might affect performance. In this short article, I will try to describe when it is necessary to use StringBuilder and when we can afford using concatenation (+ sign).

Let’s start with a simple example:

package com.imsavva;

public class ConcatenationTestApp {

    public static void main(String[] args) {
        String str = "abc";
        str = str + "def";
        str += "12" + "34" + str;


To see how it works under the hood, let’s compile and decompile it. I tried this using Java 6 and Java 8.

Compiling the code:

javac src/com/imsavva/

Decompiling the class:

javap -c src/com/imsavva/ConcatenationTestApp

Continue reading to see what happens next.

Read More →

Using one DateFormat instance per thread with ThreadLocal

DateFormat with ThreadLocal

Here is a quick tip how to use DateFormat inside a ThreadLocal field.
Why do we need that? The reason is the DateFormat class is not thread-safe but creating its instances is an expensive operation. So, this is kind of a workaround that creates only one instance of DateFormat per thread.

package com.imsavva.test;

import java.text.SimpleDateFormat;
import java.util.Date;

 * @author Savva Kodeikin
public class ThreadLocalDateFormatTest   {

    private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() {
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("dd/MM/yyyy");

    public String formatDate(Date date) {
        return dateFormat.get().format(date);

UnhandledExceptionHandler in Java: how to catch uncaught exceptions

UncaughtExceptionHandler in Java

In this short tutorial, I’m going to describe how to handle uncaught exceptions in threads. This can be done by:

  • Using threadInstance.setUncaughtExceptionHandler() ─ for a specific thread
  • Overriding ThreadGroup’s uncaughtException() method ─ for a thread group
  • Using Thread.setDefaultUncaughtExceptionHandler() ─ for all threads

If you’re interested in how to implement this, press “read more”, I’ve prepared an example.

Read More →

What is a diamond operator?

Diamond operator Java
Diamond operator Java

This is an improvement appeared in Java 7.
Consider you have a class with a long name and you need to create a HashMap of Strings and Lists of your class instances. You code will look like this:

Map<String, List<MyClassWithLongLongName>> myMap = new HashMap<String, List<MyClassWithLongLongName>>();

In Java 7 you can write less code using the diamond operator(<>):

Map<String, List<MyClassWithLongLongName>> myMap = new HashMap<>();

Describing the Java Map collection. Difference between other collections.

Map is a collection that stores key-value pairs. A map cannot contain duplicate keys.

What is the main difference between Map and other collections?

The main difference between Map and other collections is that it contains key and value. It doesn’t inherit from Collection interface.

The Map interface includes methods for basic operations (put, get, remove, containsKey, containsValue, size, empty), bulk operations (putAll, clear) and collection views (such as keySet, entrySet and values).

The general-purpose implementations are: HashMap, TreeMap and LinkedHashMap.

HashMap which is the best-performing implementation, stores its elements in a hash table. HashMap doesn’t care about ordering elements. If you need to order your elements in some order (for example, ascending, descending, etc), use TreeMap, which stores its elements in a red-black tree and uses comparators. However, if you want to store your key-value pairs in order they were inserted, consider using LinkedHashMap.

Describing the Java Deque collection interface

A Deque is a double-ended-queue. It is a collection of elements that supports the insertion and removal of elements at both end points. It implements both Stack and Queue at the same time. This interface defines following methods:

  • void addFirst(E e)
  • void addLast(E e)
  • boolean offerFirst(E e)
  • boolean offerLast(E e)
  • E removeFirst()
  • E removeLast()
  • E pollFirst()
  • E pollLast()
  • E getFirst()
  • E getLast()
  • E peekFirst()
  • E peekLast()
  • boolean removeFirstOccurence(Object o)
  • boolean removeLastOccurence(Object o)
  • + methods from Queue interface

Read More →

Describing the Java Queue collection interface

A Queue is a collection for holding elements prior to processing. It provides additional insertion, removal and inspection operations:

  • E element()
  • boolean offer(E e)
  • E peek()
  • E poll()
  • E remove()

The general-purpose implementation of Queue is LinkedList.

Each Queue method exists in two forms: one throws an exception when fails, and the other returns a special value when fails (null or false, depending on return type).
Methods that will throw an exception: add, element, remove.
Methods that will return a special value: offer, peek, poll.

Queues typically (but not necessarily) order elements in a FIFO manner, which stands for First In – First Out. In this case all new elements are inserted at the tail of the queue. Other kinds of queues may use different insertion rules.
If we need to control elements ordering we can use PriorityQueue that stores the elements in natural order or uses Comparator or Comparable to define the right order.

Describing the Java Set collection interface

A Set is a Collection that cannot contain duplicates. The Set interface extends Collection interface but has no specific methods. It adds the restriction that duplicates are prohibited. This interface also adds a stronger contract on the behavior of the equals and the hashcode methods, allowing Set instances to be compared meaningfully even if their implementation types differ. The two Set instances are equal if they contain the same elements.

JCF contains three general-purpose Set implementations: HashSet, LinkedHashSet and TreeSet. They are all based on HashMap, LinkedHashMap and TreeMap correspondly. When you add an element, it stores as a “key” of inner Map, and the value is always a dummy object.

HashSet which is the best-performing implementation, stores its elements in a hash table. HashSet doesn’t care about ordering elements. If you need to order your elements, consider using use TreeSet, which stores its elements in a red-black tree and uses comparators. However, if you want to store your elements in order they were inserted, consider using LinkedHashSet.

Describing the Java List collection interface

List is an ordered collection that can contain duplicates. In addition to the Collection interface methods, the List interface includes the following:

  • Positional access: manipulating the elements by their index in the list. This includes methods such as: get, set, add, addAll, remove.
  • Search: methods indexOf and lastIndexOf search for a specified object in the list and return its index.
  • Iteration: extends Iterator semantics to take advantage of the list’s sequential nature. With ListIterator you can traverse the list in either direction, modify list during iteration and obtain the current position of the iterator. The listIterator methods provide this behavior.
  • Range-view: the sublist method returns a sublist with a specified range of elements.

There are two general-purpose List implementations: ArrayList, which is based on an array, and which is usually the better-performing, and LinkedList, which offers better performance under certain circumstances.