0
Sponsored Links


Ad by Google
Sometimes interviewer asked you to list down the ways of converting string number to int. There are three different ways to converting the String to int. But you have to select the best one which suits for your code, below are the three different ways of converting string to int
  1. Integer.parseInt()
  2. Integer.valueOf()
  3. org.apache.commons.beanutils.converters.IntegerConverter

For performance point of view parseInt() is better because it just return you the primitive int data type whereas valueOf() method will create an Integer object. Creating an object is much and more expensive than parsing it.
For example,

StringToInt.java

package com.javamakeuse.poc;

public class StringToInt {

 public static void main(String[] args) {
  String number = "123";

  long startTime = System.currentTimeMillis();
  // 1. using parseInt method
  for (long i = 0; i < 10000000000l; i++) {
   Integer num = Integer.parseInt(number);
  }
  long diff = System.currentTimeMillis() - startTime;
  System.out.println("parseInt method completed in " + diff + " ms");

  startTime = System.currentTimeMillis();
  // 2. using valueOf method.
  for (long i = 0; i < 10000000000l; i++) {
   Integer num = Integer.valueOf(number);
  }
  diff = System.currentTimeMillis() - startTime;
  System.out.println("valueOf method completed in " + diff + " ms");

  startTime = System.currentTimeMillis();
  // 3. using convert method of
  // org.apache.commons.beanutils.converters.IntegerConverter
  IntegerConverter c = new IntegerConverter();
  for (int i = 0; i < 10000000; i++) {
   int num = (Integer) c.convert(Integer.class, number);
  }
  diff = System.currentTimeMillis() - startTime;
  System.out.println("convert method completed in " + diff + " ms");

 }

}

OUT PUT:
parseInt method completed in 223096 ms
valueOf method completed in 323592 ms
convert method completed in 433019 ms

Note: Out put will be vary for machine to machine configuration.



Sponsored Links

0 comments:

Post a Comment