Lambdas vs Anonymous Classes

So far in java we have seen interfaces and abstract classes, with a single abstract method, being used as function types. Their instances, known as function objects, represent functions or actions. Since JDK 1.1, the primary means of creating a function object was the anonymous class. Below is a code snippet to sort a list of strings in order of length, using an anonymous class to create the sort’s … Continue reading Lambdas vs Anonymous Classes

Prefer try-with-resources to try-finally

The Java libraries include many resources that must be closed manually by invoking a close method. Examples include  InputStream,  OutputStream, and  java.sql.Connection.  While many of these resources use finalizers as a safety net, finalizers don’t work very well.  For a long time, a try-finally statement was the best way to guarantee that a resource would be closed properly, even in the face of an exception or return. The above … Continue reading Prefer try-with-resources to try-finally

Static Factory vs Constructors

Generally any class allows clients to create objects by providing a public constructor. There is another technique which every programmer should be aware of. An Static Factory. A class can provide one static factory, method  which is simply an static method which returns object of the class. Note that a static factory method is not the same as the Factory Method pattern from Design Patterns. There are few … Continue reading Static Factory vs Constructors

Use of ‘this’ in Java

this keyword is a pet name for the current instance within a class. In other word, this is a reference variable that refers to the current object. this does not really affect end code. It is a compile time operator and the code generated with or without it, will remain the same. Where you have to use it, that totally depends on the context. There could be numerous place where … Continue reading Use of ‘this’ in Java

Cloneable in Java

Cloneable interface is one of the mistake in design in Java. At least I think so 🙂 A class should be implementing Cloneable interface if that class wants to be cloned along with overriding clone() method from Object class. This combination of compulsion makes it quite unusual to implement. Code below: As you can see Student Class is implementing Cloneable interface and also overriding clone() … Continue reading Cloneable in Java