Interview Questions

Java Best Practice

In this article, we will discuss about certain best practices to be followed while developing programs or applications using JAVA.

Variable Declaration
When the variables are defined, please make sure you give meaningful names. For example

String d1 = "RC221";

Instead of naming a device as d1, we can give a meaningful name applicable for the context.

String deviceName = "RC221";

Whenever you create a method inside the class, declare all the method variables and then start the program code logic. This will increase the readability.

Method Size
Please make sure the number of lines in a method is less than 20. Such methods will be easy to read and maintain. Try to have more than one method instead of having all code in a single method. When you feel that certain piece of code in a method is common for that particular module, then have it as a separate method. If that functionality is common for the entire application then move it to an utility class so that it can be used by the entire application. A Utility class is either a singleton or a static class, whose methods are common for the entire application.

Method Arguments
When you declare or define a method, please make sure that the method arguments are either interface or super types. For example, consider the following method

public void processList (ArrayList <String>  nameList)


In the above method, the argument is an Array List, which is a specific class of List interface. Instead we can have the argument of List so that we can pass any sub type of List Interface. If at all you want to pass a LinkedList in future, the method definition need not be changed. So use sub types for method arguments for exceptional cases, where it is actually required and other wise use only super types or interfaces. Super types, I mean here is the top most super class for that particular argument.

Value Objects
When you want to pass more than three arguments to a method, try using a single java bean consisting of all the arguments as member variables. That will be useful because, if there will be a requirement in future to increase the number of arguments, then the method signature will not get affected. A value object is a simple POJO or a java bean.

Code to an Interface than to Implementation
This is a golden rule in object oriented programming. Its always a best practice to code to super type (java interface or abstract class or super class) than to a direct class implementation. Whenever you start creating the class, always try to implement the interface and add your code logic in the interface methods. Consider the following example.

Public class A
    B b1;
    C c1;
    Public A()

Consider the above class A. It uses two other classes B and C within A. It would be fine that B and C are either interfaces or super types, so that even if their implementation changes in future, the code in class A will not be affected. You may have come across many such classes like Class A in your application. Try to follow this convention of coding to interface rather than implementation in you classes. This will reduce maintenance overhead. Applications created using Spring Framework usually follow this rule as a best practice.

It is always better to log errors or information in your code for debugging purpose. It will reduce the testing time. Make sure you write code to log errors wherever possible in your code, so that it will be easy to debug issues in your application. Apache Log4J open source framework can be used for logging in java application.

Use System.out.println() only for testing in the development environment. Try removing all the System.out.println() statements before you commit your code in versioning system, as they are additional overhead to you application.

Design and Development
It is always a best practice to do design stuff before carrying out the actual implementation. The process of design may vary depending on the requirement either simple or complex. If the requirement is simple such as sorting a list of
Strings, you should first write a simple algorithm or flow chart in a paper to sort a specific set of strings. If it works on paper, then go ahead and implement it in your programming language.

A good programming practice is to list down the logical steps to satisfy the requirement before implementing the code. On the other hand if the requirement is complex, such as to develop a module in your application. Then you can start with design using UML diagrams (such as class, sequence diagrams) and then land up with implementation. In any case, you will mostly end up in trouble if you start programming without proper design.

Separation of Concerns
Since Java is an object oriented programming language, Encapsulate as many classes as possible in your application. Instead of having 20 methods in a single class, have them separate as 4 methods in 5 classes. This kind of architecture will decrease maintenance nightmare. Also make sure that the methods you add in a class are logically related to the class's behavior. Don't add unrelated methods to a class. A class should always represent a single entity.

Design Patterns
Design Patterns are proven and tested design methods which you can incorporate in your application to have a flexible design and better maintenance. After getting a good knowledge on basic design patterns, try to incorporate them in your project as applicable. By using design patterns effectively, we can increase code reuse and decrease maintenance issues. Some of the basic design patterns like Factory, Singleton and Observer are available in this site.

SQL Injection
Whenever you use plain JDBC to connect to DB, always use Prepared Statement instead of Statement. There are two advantages out of it. Prepared Statements are compiled the first time when they are executed. So, they can be used for repeated executions , which increases performance. Secondly we can avoid SQL Injection, if we used Prepared Statement with placeholders. Which in turn avoids malicious SQL query being run by hackers.

Separation of SQL Queries
If you are using plain JDBC to connect to DB in a java application, try to separate out all the sql queries from your DAO layer in to a separate file. Have an interface to contain all the sql queries as constants. These application level constants can be used by other classes in your application.

Prefer Enums to Constants
If you are using JDK 1.5 and above, start using Enum classes instead of application level constants. Enums are similar to java classes, used to represent a set of constants with a value associated with each. They also have constructors and methods similar to classes. Consider the following class Signal with three final variables as constants.

class Signals
        public static final String red = "RED";
        public static final String yellow = "YELLOW";
        public static final String green = "GREEN";

Instead of the above class , we can use an Enum Signal class as follows.

public enum Signal {

        RED("Red"), YELLOW("Yellow"), GREEN("Green");

        private String value;

        private Signal(String value) {
                this.value = value;

        public String getValue() {
                return value;

        public Signal getSignal(String value) {

                if ("Red".equalsIgnoreCase(value))
                        return RED;
                else if ("Yellow".equalsIgnoreCase(value))
                        return YELLOW;
                        return GREEN;



Indirectly the above Enum class encapsulates each constants as they can have separate behavior using methods.

Method Overloading
When ever you create an Interface or Class, try to have overloaded methods. Overloaded methods implement similar functionality with varied method arguments. This will increase the usability of the Class as the user is provided with different set of options to access the same functionality.