Skip to content

java_questions

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;

        System.out.println(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/ConcatenationTestApp.java

Decompiling the class:

javap -c src/com/imsavva/ConcatenationTestApp

Continue reading to see what happens next.

Read More →

Achievement unlocked. Sololearn Java certificate.

Sololearn Java course

Yesterday I finished a Java course with the Sololearn iPhone appilcation. Just for fun. I had some free time and decided, why not to study Java on my mobile phone, so that’s how I found this app. What can I say about it? It gives very little knowledge about Java.

There are 6 sections in this course: basic concepts, conditionals and loops, arrays, classes and objects, more on classes, and the last one, exceptions, lists, threads and files. Each section contain a small piece of theory and some ordinary practical tasks. I wonder, how have developers decided to combine such large themes as collections and threads (and exceptions and files)?

I don’t know what’s the target audience of this app. If you’re a beginner, you probably shouldn’t download it, because it’d be better to read some good Java books. The application can’t give you even 1/10 of needed knowledge. If you have some Java experience, you probably won’t discover anything new.

My mark: ❤️❤️❤️💙💙💙💙💙💙💙

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

What data can be stored in a collection?

You can store anything but primitives. To store primitives consider using wrappers (Integer for int, Double for double, etc…).
For example, you can store your own classes:

List<MyClass> myClassObjects = new LinkedList<MyClass>();

To store primitives:

Set<Integer> ints = new TreeSet<Integer>();

Notice, that you can add primitives, since it will be wrapped automatically:

ints.add(1); // Correct

What benefits does JCF provide?

JCF provides the following benefits:

  • Reduces programming effort: you don’t need to invent the wheel anymore, JCF provides useful data structures and algorithms.
  • Increases program speed and quality: JCF provides high-performance, high-quality implementations of useful data structures and algorithms. Programs can be easily tuned by switching collection implementation. It is possible because interface implementations are interchangeable. When you use the Collections Framework you don’t need to waste time by writing your own data structures, so you’ll have more time to write and improve your business logic.
  • Allows interoperability among unrelated APIs: you can use collections in different applications and be sure that it will work fine. You can exchange your collections between applications seamlessly.
  • Reduces effort to learn and to use new APIs: many APIs take collections on input and return them as output. In the past, each API could implement its own collections and you needed to learn it. Now we have a universal solution – JCF.
  • Reduces effort to design new APIs: this is the reverse side of the previous benefit. A programmer don’t have to invent and to implement his own collections.
  • Fosters software reuse: if you implement your own collection with a JCF interface, you will get a reusable code. You can use collections utilities on your implementation as well.

Whas is a collection?

Collection is an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data.
Live example: several Employee objects can be grouped into a collection:

List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee(“John”));
employees.add(new Employee(“Mary”));

Java has a Java Collection Framework (JCF), which consists of:

Read More →