Thursday, 1 December 2016

Why to use Boolean.valueOf than Boolean constructor?

First let’s see the implementation of Boolean.valueOf method.

    public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }

As you see the above source code, valueOf method takes one argument ‘b’ and return TRUE, if the argument ‘b’ is true, else FALSE. TRUE, FALSE are the constants defined like below.

    public static final Boolean TRUE = new Boolean(true);
    public static final Boolean FALSE = new Boolean(false);

The variables TRUE, FALSE are defined as static final variable, that is these are immutable variables. One greatest advantage of immutable variables is that, they can’t change their state, so we can reuse these variable at any point of time. Following posts explain about the immutable classes.


In case of constructor, constructor creates new object on every call. If you are going to use same variable many times, then go for valueOf method than constructor. It improves the performance and save space.

Test.java
public class Test {

 public static void main(String args[]) {

  long time1 = System.currentTimeMillis();

  for (int i = 0; i < 100000000; i++) {
   Boolean b = Boolean.valueOf(true);
  }

  long time2 = System.currentTimeMillis();

  for (int i = 0; i < 100000000; i++) {
   Boolean b = new Boolean(true);
  }

  long time3 = System.currentTimeMillis();

  System.out.println("Time taken by valueOf method is " + (time2 - time1));
  System.out.println("Time taken by constructor is " + (time3 - time2));
 }

}



No comments:

Post a Comment