Friday, July 12, 2013

6. How to convert String “123” to Integer or int?

There are many ways of converting a String to Integer and String to int, Below are the most popular:

Converting String to Integer (not a primitive type)

1. Integer myInteger = new Integer("myString");

Converting String to int (primitive type)

1. int a = Integer.parseInt("myString"); // parseInt returns int
2. int a = Integer.valueOf("myString"); //  returns Integer

All the above statements throws exception (Java.lang.NumberFormatException) if the passed argument "myString" is not a number.

No comments :

Post a Comment