10 Most Useful Java Best Practice Quotes for Java Developers
- By Viral Patel on February 10, 2010
- Java

Quote 1: Avoid creating unnecessary objects and always prefer to do Lazy Initialization
Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact. It is thus advisable to create or initialize an object only when it is required in the code.
public class Countries {
private List countries;
public List getCountries() {
//initialize only when required
if(null == countries) {
countries = new ArrayList();
}
return countries;
}
}
Quote 2: Never make an instance fields of class public
Making a class field public can cause lot of issues in a program. For instance you may have a class called MyCalender. This class contains an array of String weekdays. You may have assume that this array will always contain 7 names of weekdays. But as this array is public, it may be accessed by anyone. Someone by mistake also may change the value and insert a bug!
public class MyCalender {
public String[] weekdays =
{"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};
//some code
}
Best approach as many of you already know is to always make the field private and add a getter method to access the elements.
private String[] weekdays =
{"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};
public String[] getWeekdays() {
return weekdays;
}
But writing getter method does not exactly solve our problem. The array is still accessible. Best way to make it unmodifiable is to return a clone of array instead of array itself. Thus the getter method will be changed to.
public String[] getWeekdays() {
return weekdays.clone();
}
Quote 3: Always try to minimize Mutability of a class
Making a class immutable is to make it unmodifiable. The information the class preserve will stay as it is through out the lifetime of the class. Immutable classes are simple, they are easy to manage. They are thread safe. They makes great building blocks for other objects.
However creating immutable objects can hit performance of an app. So always choose wisely if you want your class to be immutable or not. Always try to make a small class with less fields immutable.
To make a class immutable you can define its all constructors private and then create a public static method
to initialize and object and return it.
public class Employee {
private String firstName;
private String lastName;
//private default constructor
private Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public static Employee valueOf (String firstName, String lastName) {
return new Employee(firstName, lastName);
}
}
Quote 4: Try to prefer Interfaces instead of Abstract classes
First you can not inherit multiple classes in Java but you can definitely implements multiple interfaces. Its very easy to change the implementation of an existing class and add implementation of one more interface rather then changing full hierarchy of class.
Again if you are 100% sure what methods an interface will have, then only start coding that interface. As it is very difficult to add a new method in an existing interface without breaking the code that has already implemented it. On contrary a new method can be easily added in Abstract class without breaking existing functionality.
Quote 5: Always try to limit the scope of Local variable
Local variables are great. But sometimes we may insert some bugs due to copy paste of old code. Minimizing the scope of a local variable makes code more readable, less error prone and also improves the maintainability of the code.
Thus, declare a variable only when needed just before its use.
Always initialize a local variable upon its declaration. If not possible at least make the local instance assigned null value.
Quote 6: Try to use standard library instead of writing your own from scratch
Writing code is fun. But “do not reinvent the wheel”. It is very advisable to use an existing standard library which is already tested, debugged and used by others. This not only improves the efficiency of programmer but also reduces chances of adding new bugs in your code. Also using a standard library makes code readable and maintainable.
For instance Google has just released a new library Google Collections that can be used if you want to add advance collection functionality in your code.
Quote 7: Wherever possible try to use Primitive types instead of Wrapper classes
Wrapper classes are great. But at same time they are slow. Primitive types are just values, whereas Wrapper classes are stores information about complete class.
Sometimes a programmer may add bug in the code by using wrapper due to oversight. For example, in below example:
int x = 10; int y = 10; Integer x1 = new Integer(10); Integer y1 = new Integer(10); System.out.println(x == y); System.out.println(x1 == y1);
The first sop will print true whereas the second one will print false. The problem is when comparing two wrapper class objects we cant use == operator. It will compare the reference of object and not its actual value.
Also if you are using a wrapper class object then never forget to initialize it to a default value. As by default all wrapper class objects are initialized to null.
Boolean flag;
if(flag == true) {
System.out.println("Flag is set");
} else {
System.out.println("Flag is not set");
}
The above code will give a NullPointerException as it tries to box the values before comparing with true and as its null.
Quote 8: Use Strings with utmost care.
Always carefully use Strings in your code. A simple concatenation of strings can reduce performance of program. For example if we concatenate strings using + operator in a for loop then everytime + is used, it creates a new String object. This will affect both memory usage and performance time.
Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly. For example:
//slow instantiation
String slow = new String("Yet another string object");
//fast instantiation
String fast = "Yet another string object";
Quote 9: Always return empty Collections and Arrays instead of null
Whenever your method is returning a collection element or an array, always make sure you return empty array/collection and not null. This will save a lot of if else testing for null elements. For instance in below example we have a getter method that returns employee name. If the name is null it simply return blank string “”.
public String getEmployeeName() {
return (null==employeeName ? "": employeeName);
}
Quote 10: Defensive copies are savior
Defensive copies are the clone objects created to avoid mutation of an object. For example in below code we have defined a Student class which has a private field birth date that is initialized when the object is constructed.
public class Student {
private Date birthDate;
public Student(birthDate) {
this.birthDate = birthDate;
}
public Date getBirthDate() {
return this.birthDate;
}
}
Now we may have some other code that uses the Student object.
public static void main(String []arg) {
Date birthDate = new Date();
Student student = new Student(birthDate);
birthDate.setYear(2019);
System.out.println(student.getBirthDate());
}
In above code we just created a Student object with some default birthdate. But then we changed the value of year of the birthdate. Thus when we print the birth date, its year was changed to 2019!
To avoid such cases, we can use Defensive copies mechanism. Change the constructor of Student class to following.
public Student(birthDate) {
this.birthDate = new Date(birthDate);
}
This ensure we have another copy of birthdate that we use in Student class.
Two bonus quotes
Here are two bonus Java best practice quotes for you.
Quote 11: Never let exception come out of finally block
Finally blocks should never have code that throws exception. Always make sure finally clause does not throw exception. If you have some code in finally block that does throw exception, then log the exception properly and never let it come out :)
Quote 12: Never throw “Exception”
Never throw java.lang.Exception directly. It defeats the purpose of using checked Exceptions. Also there is no useful information getting conveyed in caller method.
More Quotes from Java Developers
Do you have a quote that is not included in above list? Well, feel free to add your Java best practice quote using comment below. Write your quote and explain it in 2-3 lines. I will add all those user generated quotes in this section.
Quote #13: Avoid floating point numbers
It is a bad idea to use floating point to try to represent exact quantities like monetary amounts. Using floating point for dollars-and-cents calculations is a recipe for disaster. Floating point numbers are best reserved for values such as measurements, whose values are fundamentally inexact to begin with. For calculations of monetary amounts it is better to use BigDecimal.
Get our Articles via Email. Enter your email address.



Hey great list…
Here is one from me.
Quote #13 Avoid floating point numbers
It is a bad idea to use floating point to try to represent exact quantities like monetary amounts. Using floating point for dollars-and-cents calculations is a recipe for disaster. Floating point numbers are best reserved for values such as measurements, whose values are fundamentally inexact to begin with. For calculations of monetary amounts it is better to use BigDecimal.
Thanks Mark..
I have added your quote as #13 in above list :)
Nice list! Thanks for the advice!
I like this list: it might seem simple at first, but it can actually save a lot of troubles down the road.
Nice work!
p.s. I think there is a typo in the first sentence of quote 3: I think you meant to say “Making a class immutable is to make it unmodifiable
Did you mean immutable here?
“Making a class mutable is to make it unmodifiable. “
Item 2.
A better solution would be to return an unmodifiable list rather than an array.
You have also made some statements about performance re primitive types and strings that might not always be relevant. The JVM and Hotspot does some amazing things these days and as a result some of these statements should be backed up by statistics.
On our large enterprise project we use concatenation and wrapper objects a lot and they are rarely the source of performance issues. We have used the Netbeans profiler to test them.
Poor design is by far the biggest problem, for instance; returning primitive types for keys leads to lockin that you may well regret later.
One more tip is the use of final. We use this where possible on member variables and on all parameters. This has quashed more bugs than anything – especially in the area of cut n paste!
>>> Do you have a quote that is not included in above list?
I think it is done already, e.g. Effective Java Second Edition by by Joshua Bloch or Implementation Patterns by Kent Beck.
BTW about tips #1 – Lazy Initialization is very bad approach in case of concurrency, you have to synchronize getter for getCountries() while object creation is not so expensive, look at http://www.ibm.com/developerworks/java/library/j-jtp04223.html “The performance impact of object creation, while certainly real, is not as significant in most programs as it once was or is still widely believed to be.”
Felt motivated reading this. I am a Java developer and i am very eager to create some new, innovative application some day. That is why i am going to attend Sun Tech Days 2010 conference in Hyderabad. Experts are going to share ideas on new technologies there. lets see what happens.
A very useful list of pointers for Java devs. Thanks a ton!
Quote 7:
Why using “Integer x1 = new Integer(10);” anyway… it’s the old way, it’s slow and it creates a new instance.
Instead: use “Integer x1 = Integer.valueOf(10);” or use the automatic boxing/unboxing with “Integer x1 = 10;”.
Quote 9:
The “always” is simply not neccessary.
Sometimes there is no collection I want return, e.g. in case of error.
I don’t need an exception here nor want I know, why this Collection is null: there was an error and I don’t want to work on this list, not even on an empty list.
Sure, returning null on error needs to be documented in some way. Other way round, always returning a collection/array (even if empty) needs to be documented either.
I suppose better: “Quote 9: Prefer to return empty Collections and Arrays instead of null”
“Quote 3″ and “Quote 10″ correspond to each other, don’t they? I think, they describe the same principle on another level.
“Quote 11″: maybe a reference to “apache-commons-io” and “apache-commons-db” would be helpful, since they introduce “DbUtils.closeQuietly(conn/rs/stmt);” and “IOUtils.closeQuietly(reader/stream/etc.);”
@Firass @Jason Thanks for pointing out the typo. I have corrected this now.
You do not need a private constructor to make an object immutable. Immutable just means the state of the object cannot be changed, therefore an object with no accessors to the field is immutable (if none of the methods change the state either). The valueOf method is not required at all.
Sure Koalition, I agree with you in this. But the above example is just to make sure that the class is not overridden by writing a subclass and manipulating its field in subclass.
Ofcourse this is not needed in most of the cases when we can just make sure a class is immutable by using either defensive copies or other mechanism.
quote 1 is silly unless you are creating ridiculous number of objects. classic case of premature optimization. added complexity for very very little benefit usually.
quote 2: I don’t buy this, if you need a really lightweight data class, why add boilerplate? if you start making the class more complex, ditch the public fields
quote 3-7: agree
quote 8:
“For example if we concatenate strings using + operator in a for loop then everytime + is used, it
creates a new String object”
wrong. the compiler handles most of these cases. used to be true, not any more. if you are in a tight loop building a string, the compiler can’t handle this case, so using the stringbuilder class is appropriate.
Re Quote 1:
In Effective Java – Item 71 – Use lazy initialization judiciously Bloch says “don’t do it unless you need too” – and the example you have isn’t thread safe either.
Quote 14:
Do not take engineering advice from a blog.
quote 1 is silly unless you are creating ridiculous number of objects. classic case of premature
+1.
This is very bad example. quote 1 only makes sense, if it computationally expensive (and then you would need to synchronize the block)
Why would you not make an array of week names final? Or better yet, make it an enum? It’s not like the days of the week change very often….
I agree with Vic above. You knowledge of performance related to object creation and garbage collection is out of date.
“Wherever possible try to use Primitive types instead of Wrapper classes”
Please don’t take this advice. It’s called “primitive obsession”, and it makes your code harder to understand and refactor.
The author seems obsessed with focusing on performance issues that may not even be of concern in a particular application.
Don’t focus on performance first. Focus on good design and communicating intent first.
The performance problems will never be where you think they are anyway. Optimize when you know you have a problem and you know where it is (use a profiler).
Nice and useful tips. However I cannot agree with Quote 12. Throwing exceptions is not always a bad option.
>> Quote 1: Avoid creating unnecessary objects and always prefer to do Lazy Initialization
really?
Viral why wee need this method in Empoyee in Quote 3?
public static Employee valueOf (String firstName, String lastName) {
return new Employee(firstName, lastName);
}
and making constructor private?
Don’t you think making instance variable private is enough?
I agree with you in this. But the above example is just to make sure that the class is not overridden by writing a subclass and manipulating its field in subclass.
Ofcourse this is not needed in most of the cases when we can just make sure a class is immutable by using either defensive copies or other mechanism.
How come you modify private in subclass?
Is it not always good to clone the Class as and when required and access the variables, rather than having getter method do a clone. this would give more flexibility to the designing.
Hi,
I tried some of the examples that you gave and I got different results. Is this ‘coz of Java 6?
Ex:
int x = 10;
int y = 10;
Integer x1 = new Integer(10);
Integer y1 = new Integer(10);
System.out.println(x == y);
System.out.println(x1 == y1);
Result:
true
false
Good list, thanks for the tips.
Mayur, You are getting these result because in first case you are comparaing the primitives using == operator that compare the value that is 10 so it is printing 10 but in second case you are comparaing references Wrappers are just class object values are 10 but the references are different that is why you are getting false
Nice Tips…thanks :)
“To make a class immutable you can define its all constructors private and then create a public static method”
If you want to make the class to be immutable, then simply don’t provide the mutators (setter methods), in addition to data hiding (private member variables). I don’t see how making a constructor private in combination with public static method addresses immutability!. I’m puzzled.
Nice list! Thanks
very informative.
Very good list of best practices at the core java programming level !!!