How to create and write to a file in Java

January 29, 2017

In this short tutorial, we will discuss how to create and write to a file in Java.

1. Creating file with PrintWriter

We will be using* package. We will create a file. And by using PrintWriter object we will write to it.

At the beginning we should create the file:

When we have our file created, we can now write to it using PrintWriter class.

It is worth to say, that in this constructor we don’t use our object but the file name directly. On that point, we should add an exception to our main method in case file doesn’t exist.

Now, using our freshly made writer we can easily add new lines of text to our file:

When we decide that we won’t be using our file more we need to remember about closing the PrintWriter.

2. Creating file using Files and Path classes

Another way to create and write to a file is Files class included in java.nio.file.* package. It is a little bit less intuitive but still worth to know. It was introduced in Java 7+. The methods used here are: asList(), get(), and write().

Firstly, we will create all lines of our text using List.

Then, we should specify the name of the file using Path class

and after all, we can create a full file using the previous objects:

And that’s it! It’s different but quicker because we don’t need to write line by line. In this method, we write text at once.

Difference between wait() and sleep() in Java

January 16, 2017

In this short post, we will discuss the difference between wait() and sleep().

In simple words sleep() hold on the process in memory for specified time while wait() releases the monitor and keeps “waiting” until calling the notify() method.

Wait() is used when we want to communicate between specified threads. Sleep() is just for mere pause for a thread.

1. Sleep

Thread.sleep(n) means that we send it into “timed waiting” state for n time where is a number of milliseconds (or even nanoseconds if we want to, the method has got 2 arguments then). For example, when n = 10000 it means it will be waiting for 10 000 milliseconds (which is 10 seconds).

Another crucial thing about sleep() is that it’s a static method. We can use it only for the current thread and for that one it will be affected. We cannot sleep() thread other than current one.

However, we can release the sleeping thread from another one (and of course from the current one) using thread_name.interrupt() method as you can see in this short example:

Afterward, it is the time to show more complex example:

This code prints:

2. Wait

This method is very similar to the previous one although we use it for an object. This kind of object is needed for thread synchronization, and we name it “lock object”.

And now lock.wait() sends the thread to “waiting” state and make space for other processes to execute. Actually, lock.wait() moves it to some waiting list. The only way to move it out is to use the notify() or notifyAll() method. This is important because it’s the only way to let the process/thread to work again. The whole synchronization which helps the program with memory management take place in a synchronized method. All of these we will show in the example below.

In the first thread, we can do some instructions, wait for the second process to execute and continue at the exact point when it paused. This is the result of our code:


How to convert a stack trace to String

December 26, 2016

In this post, we will convert a stack trace to String. There are multiple methods for doing this.

1. Using StringWriter and PrintWriter

The first method is to use StringWriter and PrintWriter classes. Let’s have a look on a below example.

In the first line, we create an instance of the StringWriter class. After that, we create an instance of PrintWriter using previously create StringWriter. Nextly, we use the Throwable.printStackTrace(PrintWriter) method to print the Exception stack trace to the printWriter object. Lastly, we print the exception stack trace, which is now stored in stringWriter.

2. Using Apache Commons Lang – ExceptionUtils

The another method is to use the ExceptionUtils.getStackTrace(Throwable) method.

This method simply gets a stack trace from a Throwable as a String. The String’s content is exactly the same as in the example above.

3. Using Google Guava – Throwables

You can also use the Throwables.getStackTraceAsString(Throwable) method.

The variable content is now exactly the same as in the first example.

Convert array to ArrayList in Java

December 23, 2016

You can convert arrays to ArrayList by using this method:

1. Convert Integer array to ArrayList

In the first line of above code, we declare an array of Integers. In the second line, we convert this array into ArrayList. Lastly, we print the integerList.

The output of the above program is:

2. Convert String array to ArrayList

When it comes to Strings the things are very similar. You can see it in this example:

The output of the above program is:

3. Convert primitive type array to ArrayList

Next, we will consider arrays which have primitive types.

In this example conversion is simple. At the beginning we declare intArray. Nextly, we declare a new integerLit. After that we copy each element of intArray into integerList. The output of execution of this program is:

String concatenation and StringBuilder comparison in Java

November 27, 2016

In this post, we compare String concatenation and StringBuilder.

1. String concatenation

Strings are immutable. So we can’t change existing String, every time Java create a new String to replace previous one. String concatenation is adding two strings using operator +;

The result of executing the code above is:

2. StringBuilder

StringBuilder is a mutable sequence of characters. When you want to add new string you have to use append() method.

The result of executing the code above is:

3. Compare

String concatenation has the same bytecode as StringBuilder, but if you want to concatenate many times in loops create an instance of StringBuilder every time, and it will be slower than string builder.

loopAmount String concatenation StringBuilder
1000 11 ms 3 ms
10000 615 ms 101 ms
50000 8937 ms 2130 ms

When using StringBuilder?

You should use StringBuilder when you use

  • concatenation in loops
  • concatenation using multiple threads

Otherwise, use string concatenation to the code clarity.

What is @Override annotation and when to use it in Java

October 13, 2016

@Override Annotation tells the compiler that this method overrides a superclass method.
This annotation is optional but is good practice to use it whenever you override a method.

In above example, we override print method and use @Override Annotation

Why should you use @Override Annotation?

When you use this annotation compiler will generate error when

1. You misspell method name, parameter name, parameter type.

Without @Override when you misspell name/parameter, subclass method would behave as a new method.

2. You change the signature of overridden method, and you can quickly find all class that requires the change of name.


How to convert int to String in Java.

October 4, 2016

To convert int to String in Java you can use:

1. Integer.toString(int i) method:

The String method takes Integer.toString(int s) an int as an argument and returns a String object.

This example uses Integer.toString(int i) to convert int to String. Result of above code is:

2. String.valueOf(int i) method:

The String method takes String.valueOf(int s) an int as an argument and returns a String object.

In above example, we’re using String.valueOf(int i) to convert int to String. The last line will print:

3. String concatenation:

You can just add int to empty string, its returns a String object;

The example above convert primitive integer value to String object using String concatenation. Below is the output of the above code:

C++ Pair class equivalent in Java

September 30, 2016

In the standard Java library, there is not Pair class. When you want to use Pair you have some options.

1. Create new class.

For example, you want to create a pair of name-price items; better is create a new class, containing field name and price. It will improve code readability, and you can add own method unique to the product.

2. Use one of many similar implementations based on key-value

For example, you use:

  • javafx.util.Pair

and access it:
  • java.util.AbstractMap.SimpleEntry

now you can get key/value:

3. Implementing own Pair class

You can also create it, below I show a basic example of own Pair class:

Now when you have Pair class you can create new Object:

and access field by:


Difference between StringBuffer and StringBuilder in Java

September 11, 2016

First, we have to remember that String is immutable and final in Java. Every modification of String (concatenation, substring, converting into lowercase or uppercase) creates a new String object. StringBuffer and StringBuilder are classes which allow us to manipulate String without creating garbage.

Append method implementations

What is the difference between them? Let’s look at the implementations of the method append(int) from StringBuffer and StringBuilder.



Because each method of StringBuffer is synchronized, it is thread-safe. However, because of that, it’s also slower. StringBuilder provides an API compatible with StringBuffer, but it is more efficient, as it has no synchronized methods.

Performance test

Let’s do a performance test of those two classes. The code below measures the time of 108 appends of a single char ‘a’.


The result shows that execution time of StringBuilder’s methods is almost six times faster than StringBuffer’s methods. That is the reason why we should use StringBuilder rather than StringBuffer.

How to compare enums in Java

September 6, 2016


The best way to compare enums in Java is == operator, like in an example below:

Comparison of == and equals methods

There are two ways to compare enums in java: == operator and equals() method.

First of all, I would like to show you an implementation of method equals() of java.lang.Enum:

As you can see, the equals() method of java.lang.Enum uses the == operator. This means you can use both to compare Enums. So, when we run the code below:

The result is:

But due to == being an operator and equals() being method, there are subtle differences.

Using equals() can cause NullPointerException

Let’s declare two variables of type Color:

and compare them using == operator:

Everything is alright because if we compare any Enum with null like this, it will print false.

But if we try to compare those variables using equals() method:

we will get NullPointerException.

== operator provides compile-time checking

Compile time safety is another advantage of using == operator. This operator checks if both objects are the same enum type at compile time. Equals() method does not do that because of contract (Object.equals(Object)), so we can expect a RuntimeException.

We should use an == operator, since detecting errors at compile time is always better.

Page 3 of 4

Privacy Preference Center