Java tips

How to clear an array ?

By setting an object to null, we marks it as able to be garbage collected. But to avoid bad surprises, we should also clear the collections. With a collections being part of java.util package, we can ...

Continue Reading →

How to track the last element of one line with RegEx ?

Sometimes we need to get the last element of the line. We can do it by mesuring the line length and getting the character through String's charAt(int) method. However, we can rarely deal with the Stri...

Continue Reading →

What is the difference between File.mkdir() and File.mkdirs() methods ?

The difference is hidden under the "s" which is missing in the first method. In fact, mkdir() will create only demanded directory. If some of parent directories doesn't exist, this method will return ...

Continue Reading →

How to make a screenshot ?

Making a screenshot in Java is quite simple thanks to java.awt package with a lot of graphical tools. First, take a look at the sample code: public class ScreenshotTest { @Test public void te...

Continue Reading →

How to sort TreeMap in reverse order ?

By default, TreeMap stores the entries in ascending logic, from the smallest key to the biggest. Take a look on this sample: @Test public void normalTreeMap() { Map<String, String> alphabet =...

Continue Reading →

How to concatenate two arrays ?

Java's array concatenation is always as simple as in PHP with array_merge method. In Java we need to use System.arraycopy() or org.apache.commons.lang.ArrayUtils.addAll() method. There are the code sa...

Continue Reading →

What is static import ?

Sometimes we can use static imports instead of normal imports in Java. We can do that, for example, for JUnit assertions as assertTrue or assertFalse. We can also use it for some of java.lang.Math com...

Continue Reading →

What does UnsupportedClassVersionError mean ?

Sometimes you can meet a strange java.lang.UnsupportedClassVersionError exception. As we can read at Javadoc, this exceptions is thrown when the JVM's JDK doesn't support JDK used to compile the class...

Continue Reading →

How to iterate large numbers with small int range ?

Imagine a for loop iterated 20 times and an array containing only 5 elements. How we can ensure that all elements will be printed inside the loop exactly 4 times ? Take a look on following sample: ...

Continue Reading →

How to generate dynamic JSP include ?

You can't generate JSP code programmatically, for example given String "<% include file="template.jsp" %>", and use it directly in the JSP. In our case, this code won't include template.jsp, but on...

Continue Reading →