Last Updated:

7 Small Tips for Java Beginners

In this article, I picked up 7 simple but effective practices for novice Java developers.

We prefer "lazy" initialization

It is desirable to create or initialize objects only when necessary. For example, lazy initialization is useful when the initialization process itself is associated with a heavy operation, such as a database query.

To check the string for emptiness, use the isEmpty() method

There are several options for checking a string for emptiness. One of the most popular is the method - do not write like that.
The best way to check a string for emptiness is to use the . This method simply compares the length of the string to zero using the , method, so this operation is less expensive.

See the source code of these methods:

Source code :isEmpty()

Source code :equals()

The difference is obvious.

Return empty collections instead of null

If the function returns an empty collection, then we need to make sure that it is the empty collection that is returned, and not the . This will save you from additional checks on:nullnull

Use strings wisely

If two rows are merged with a "+" in a loop , a new String object is created each time. This increases memory consumption and code execution time, especially when working with large amounts of data. We also try not to use the constructor when creating a string:for

To concatenate strings, use a special class.StringBuilder

We use primitives instead of shell classes

Wrapper classes run slower than primitives because they store additional information, and primitives are only values.
Sometimes we can make a mistake in the code using a wrapper class, for example:

The first output on the screen will print, the second will output. The problem is that you can't use the operator , to compare two shell objects, because it compares references rather than the actual value.truefalse==

We try not to throw java.lang.Exception


We try not to quit, as this is contrary to the purpose of using exceptions. You need to throw more specific exceptions or create your own if you have not found the right one for a particular

Handling nullPointerException correctly

The exception is one of the most common in Java. It occurs when we try to access a method or field of an object that references . In this case, some novice programmers process using the . The correct way is to check the field for :


Here is a small note for novice Java developers. Stay tuned!