Skip to content

Java Core

Possible class names in Java

What would be the result of execution of the following code?

package com.imsavva;

public class Test {
    public static void main(String[] args) {
        System.out.println(new _成分$().getGreeting());
    }
}

class _成分$ {
    public String getGreeting() {
        return "Hello";
    }
}

If your answer is “Hello”, then you’re right!
You can use any characters from the Unicode charset, in any case, to name classes (as well as variables and methods), except some preserved words like “null”, “volatile”, “public”, etc.

However, it’s strongly recommended to stick with the Java code conventions. The rules related to the class names are on page 10.

First two reasons to use the code conventions to me are:

  • Readability – I would love to meet class names like “Eyjafjallajökull” from time to time. But, the rarer the better.
  • Convenience for programmers from different countries – imagine the situation when you have to work with the code where class names contain symbols that are missing on your keyboard? 🙈

Switch case and default

int i = 0;

switch (i) {
    default:
        System.out.println("1");
    case 1:
        System.out.println("2");
    case 2:
        System.out.println("3");
}

This snippet will compile and run without issues. It might be dubious whether it’s okay to put the “default” block at the first place, but you can place it anywhere. In this case, the result would be:

1
2
3

However there is a good practice to put the “default” block at the end of the switch statement. Or avoid using switch statements at all. 🙂

Variables and fields instantiation

package com.imsavva;

public class Test {
    private String testField;
    
    public static void main(String[] args) {
        String testVariable;
        System.out.println(testVariable);
    }
}

This code won’t compile because of line 4:

When we declare a local variable, it must be initialized before use. Class fields don’t have to be initialized. In case we didn’t specify any value, a default value will be used.

The following list represents default field values:

    private byte b;     // 0
    private short s;    // 0
    private int i;      // 0
    private long l;     // 0
    private float f;    // 0.0f
    private double d;   // 0.0
    private char c;     // '\u0000'
    private String str; // null

1Z0-808 Preparation notes

The process of studying Java Core. The picture was taken from Unsplash.com.

During the preparation time, I was making notes to remember little tricks that I didn’t know or forgot. Although I would never recommend using some of the pieces of code from the notes in production, they might be helpful for those who are preparing for the exam.

So, as I mentioned in this post, I will do my best to keep my New Year’s resolution and post the most useful notes in my blog. Along with the main topic I will try to explain why some of the code examples should never appear in your production code.

All the posts related to this topic will be marked with a tag 1Z0-808.

Passed the Oracle 1Z0-808 certification

Good news, everyone!

Even though this is the first blog in 2018, I’m still alive and I’m happy to say that I have passed the Oracle Certified Associate exam with 94% of correct answers (I still can’t believe it 😱).

It took about a month to prepare and I was spending all my free the time after work to read a book and write and test code examples.

While preparing, I have made more than a hundred of small notes, and I hope to find time and motivation in the next two months to post them here.

See you in 2019 🙂🎄

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 →

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>() {
        @Override
        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.