Java Tips and Tricks

Today I will share with you some tips and tricks for writing better Java code.

  1. There is a simple rule for a better and cleaner code called the: 10-50-500.
    10: No package can have more than 10 classes.
    50: No method can have more than 50 lines of code.
    500: No class can have more than 500 lines of code.
  2. Avoid unnecessary object creation by creating the object only on request or when necessary. For example:

    public class FacebookGroup{
    private List users;
    public List getUsers(){
    if(users == null){
    users = new ArrayList();
    return users;

  3. In order to check for odd values use the following  optimized formula – it handles negative odd numbers too.

    (num & 1) != 0

  4. To calculate powers it is preferred to use the multiplication operation than the Math.pow() function which is 300-600 times slower
  5. Use the StringBuilder class to append strings. It is faster and more optimal than appending strings using the + operator. Example:

    StringBuilder builder = new StringBuilder();
    builder.append(“Hello “);
    return builder.toString();


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s