Java Best Practices Guide

A good programmer is one who write programs (not just code). It means writing the code units which are independent enough to be re-used in multiple ways, and still they remain robust.

So let’s start identifying and learning some java best practices which can transform any code into the programs.

1. Java Design Best Practices

Following java best practices are mainly focused on system design time considerations. They are mainly useful for senior developers. Eventually, you will also be senior if not today. Why not better prepare?

8 signs of bad unit test cases

Bad unit tests are reality and everyone who does code review, face it occasionally (may be regularly). So what constitute a bad test case? How to identify bad test cases?

5 class design principles [S.O.L.I.D.] in java

5 most recommended design principles, you should keep in mind, while writing your classes. These design principles are called SOLID, in short.

Unit testing best practices

It’s overwhelmingly easy to write bad unit tests that add very little value to a project while inflating the cost of code changes astronomically. Learn how to write them correctly.

A new approach for exception handling

A new approach uses static inner classes for every new exceptional scenario. Worth reading for future software designers.

Java exception handling using inner classes

Covering some well-known and some little known practices which you must consider while handling exceptions in your next java programming assignment.

Java executor framework best practices

Some best practices which you need to keep in mind while designing your next multi-threaded application.

5 Reasons You Should Consider Migrating Your Legacy Systems

There are several reasons for migrating from old legacy systems to new advanced systems. Here are 5 of them.

13 best practices for writing spring configuration files

13 best practices for writing highly maintainable spring XML configurations.

2. Java Coding Best Practices

Following java best practices are focused on considerations to make while you hit the keyboard and start typing actual program. They are mainly useful for developers/programmers at all levels.

Generating secure password hash (MD5/SHA) in production

User provided password are generally very weak and easy to guess. There are many hashing algorithms in java, which can prove really effective for password security for your applications and your users.

Serializable interface guide

We all know what Serializable interface does. But do we really know, what changes in your class can break your design?

Object initialization best practices

Creating new objects is always an expensive process. Let’s learn how java utilize object pooling to solve this problem.

How to make a java class immutable

An immutable class is one whose state can not be changed once created. There are certain guidelines to create an class immutable. Let’s learn them.

Consider reloading log4j levels on runtime

Learn how to use WatchService to reload your logging configuration at runtime. Use them to reload other configurations as well.

Override toString() effectively with ToStringBuilder

ToStringBuilder is a utility class provided by apache commons lang library. Learn to use it to write highly customized toString() methods.

Use array instead of Vector.elementAt() inside any loop

Vector doesn’t need additional synchronization while accessed from multiple threads but it degrades its performance for the same reason. Measure it’s impact.

Always use length() instead of equals() to check empty string in java

Best way to check if string is empty or not is to use length() method and not equals(). Why? Let’s do some reasoning.

3. Java Performance Best Practices

Following java best practices can boost the performance of your java application and take it to next level. Learn them hard and keep in mind always.

Performance comparison of different ways to iterate over HashMap

Let’s see different ways to iterate over HashMap and see the differences in terms of performance they can bring.

Performance comparison of different for loops in java

Let’s compare performance of different for loops as well. They are everywhere in any program.

Best practices to improve JDBC performance

Database access is major part of any application. If you are using simple JDBC then this one is for you.

More to come …

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

13 thoughts on “Java Best Practices Guide”

  1. hi sir I’m Sriharsha,i had heard your name a lot so I want a small help from you. I’m the beginner student can you guide me by some small programs.
    would you please send me some minimum knowledge programs should be learned for my mail-sadhutarun00@gmail.com.

    whoever saw this comment , would you want to give any suggestions . send to the given above mail id.

  2. can anybody give me a whole program of how to create a game in java programming language? well it should be somewhat long enough…it wil be helpful guys if you help me slove this…..(other than tic tac toe)

  3. Hi,
    can u help me?Plz tell me how to fetch data from database and data generate in xlsx sheet.I have created program but some errors are found.so plz check my code and remove errors.If i select generate xls button to show xls sheet with fetching data.
    my code as mention below:-

    package fetch;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import javax.swing.*;
    import java.sql.Connection;
    import java.sql.*;
    import java.io.IOException;
    import java.io.FileOutputStream;
    import java.io.FileNotFoundException;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;

    public class Fetch extends JFrame implements ActionListener
    {
    JButton Ok,generate_xls;
    JLabel UserName;
    JTextField UNTF;
    JComboBox b1;
    String UN;
    String source;
    Connection conn;
    Statement st;
    ResultSet rs,rs1;
    Fetch()
    {
    super(“Data Fetch”);
    this.setLayout(null);
    this.setSize(400,400);

    try
    {
    Class.forName(“com.mysql.jdbc.Driver”);
    conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/wiprodev”,”root”,”root”);
    st=conn.createStatement();
    }
    catch(ClassNotFoundException | SQLException e)
    {
    }
    UserName=new JLabel(“UserId”);
    UserName.setBounds(15,48,120,20);
    add(UserName);
    b1=new JComboBox();
    b1.addItem(“-All-“);
    b1.addItem(“spal”);
    b1.addItem(“abkas”);
    b1.setBounds(100,50,100,20);
    add(b1);
    Ok=new JButton(“Ok”);
    Ok.setActionCommand(“Ok”);
    Ok.addActionListener(this);
    Ok.setBounds(150,250,90,40);
    add(Ok);
    generate_xls=new JButton(“Generate xls”);
    generate_xls.setActionCommand(“Generate xls”);
    generate_xls.addActionListener(this);
    generate_xls.setBounds(250,250,120,40);
    add(generate_xls);

    }
    public void actionPerformed(ActionEvent ae)
    {
    if(source.equals(“Generate xls”))
    {

    }
    try
    {
    ResultSet rs= st.executeQuery(“Select a.lead_created_by,b.userid from wp_tra_lead a,wp_mtr_user_login_trace b where a.lead_created_by=b.userid”);
    source=ae.getActionCommand();
    switch(source)
    {
    case “Generate xlsx”:
    new Fetch().show();
    break;
    case “OK”:
    new Fetch().show();
    }
    }
    catch(Exception e)
    {

    }

    try
    {

    XSSFWorkbook workbook=new XSSFWorkbook();
    XSSFSheet spreadsheet=workbook.createSheet(“Leap”);
    XSSFRow row=spreadsheet.createRow(1);
    XSSFCell cell;
    cell=row.createCell(1);
    cell.setCellValue(“userid”);
    cell=row.createCell(2);
    cell.setCellValue(“lead_created_by”);
    int i=2;
    while(rs.next())
    {
    row=spreadsheet.createRow(i);
    cell=row.createCell(1);
    cell.setCellValue(rs.getString(“userid”));
    cell=row.createCell(2);
    cell.setCellValue(rs.getString(“lead_created_by”));
    i++;
    }
    FileOutputStream out=new FileOutputStream(
    new File(“Data.xlsx”));
    workbook.write(out);
    out.close();
    System.out.println(“Data.xlsx written successfully”);

    }
    catch(Exception e)
    {

    }
    }
    public static void main(String[] args)
    {
    Fetch obj=new Fetch();
    obj.setSize(400,400);
    obj.setVisible(true);
    obj.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    }

    Thanks & Regards,
    Anil

  4. Hi Lokesh,

    I have very basic question.
    In our application, there are lot of java classes which are not used by any of the classes. initial days of the application we used to use all these classes, but over the course of time these classes are of no use and no where referring.

    Wanted to know if there will be any kind of impact on the application performance or memory wise or any other factor ?

    I see there is change in size of ear file, wanted to know if it really matters ?

    Thanks.

    • Hi Ravi, I do not think that there could be any performance overhead. Only thing which could happen is slight delay in compilation. Other than this no impact in runtime.

  5. HashMap does not take both key and value in primnitive type but we can store primitive type easily like

    HashMap h=new HashMap();

    h.put(1,1);

    both values are primitive not object

Comments are closed.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.