Useful Java basic tips for developers

This post is to boost up the development speed. In our day-to-day coding when we are writing code in Java, it’s useful to know some tips and shortcuts. These basic tips speed up the development time. In most cases, the tips are proven so less chance of making mistakes.

As people talk about the verbosity of Java, using these tips can be helpful in the case of verbosity. Java still dominates the server end of enterprise apps so knowing Java tips are always good.

Following are some basic tips for Java developer:

Empty string or null check

There are many ways to check empty string or null in Java. But we can easily use the Apache commons StringUtils. In StringUtils they have covered empty and null check in one method. Lets check the following example:

String nameStr = "";
System.out.println(StringUtils.isEmpty(nameStr)); // true

nameStr = null;
System.out.println(StringUtils.isEmpty(nameStr)); // true

If you don’t want to use Apache commons then you can simply write the following line:

String str;
if(str != null && !str.isEmpty()) { 
   // Write your code here
}

Return empty list from function

Let say in a case we need to return an empty list from a function. We can very easily do this using Java Collections Utlils. We can use the following line:

return Collections.emptyList();

Replace all spaces with a dash in string

We can use Java standard method or use regular expresstion to relace all spaces with dash in Java. Following is the line that uses Java replaceAll method to replace all spaces to dash in Java

String nameStr = "Joe Smith";
nameStr.trim().replaceAll(" +", "");

Boolean true check

We can easily check Boolean true using the following line:

Boolean isExist = true; 
if (Boolean.TRUE.equals(isExist)) {
    System.out.print("Exist");
}