Pages

Tuesday, April 9, 2019

Java Program To Convert String to int or Integer

How to convert a String to Integer wrapper class or int primitive type?
Differences between Integer.parseInt(String s) and Integer.valueOf(String s)?

Converting Java String to Integer:

In some cases, we may be getting numbers in format of String so need to convert to integer for our process.

Eg. Given string like "9876" than result would be 9876 int type.


We can perform Java String to Integer operation in 3 ways. 
1) Integer.parseInt(String s) method  
2) Integer. valueOf(String s)  method 
3) Integer Constructor



Convert Java String to Integer or int



1) Integer.parseInt(String s) method:


Integer is in package of "java.lang.Integer" and wraps primitive type to Object representation.

Method parseInt internally does read character by character using charAt() method in String class and convert it into int format.
parseInt(String number) returns int primitive type.

Integer.parseInt Example



package com.java.w3schools.core.initializer;

public class StringtoInteger01 {

    public static void main(String[] args) {

        // String to integer

        int number = Integer.parseInt("1234");
        System.out.println("Number :: " + number);
    }
}

Output:


Number :: 1234

Eg. Integer.parseInt("ABC123");


2) Integer.valueOf(String s)  method:


Integer class has a method valueOf declared as Static. So directly can access method with class name.

valueOf() method internally operates

a) invokes parseInt() methods.
b) In addition, operates on static variables of IntegerCache class which holds values on Integer[] array.
c) This returns Integer wrapper class object.

Integer.valueOf() is equivalent to new Integer(Integer.parseInt(s)).

For both methods , We should input only numerics in format of String. Apart from numerics, if give alphabetics will result in "NumberFormatException"
    number = Integer.valueOf("-4567");

    System.out.println("number :: "+number);


Output:

number :: -4567


3) Integer Constructor:


By passing string to the Integer constructor which  has parameter String literal. internally uses parseInt method.

Syntax:


new Integer(String s);


    number = new Integer("9999");

    System.out.println("Constructor number : "+number);


Output:


Constructor number : 9999

No comments:

Post a Comment

Please do not add any spam links in the comments section.