tags (space-delimited): Java
In most cases, users submit their input through a text box or text field. The content that a user enters through a text box or text field is usually in string format. And what you often need is the integer form of the content. For example, age, phone number, and so on. Java provides a number of useful and simple ways to make it easier to convert a string to an integral or integral form to a string. In this article, we will discuss different methods of string rounding and integral-type spin strings. How to convert a string to an integral type in Java
There are two optional ways to convert a string to an integral type in Java. One is Integer.parseint () and the other is ingeger.valueof (). Both of these methods are static methods in the Java.lang.Integer class. When the input string is not a valid integer, both methods throw a NumberFormatException exception. The main difference between integer.parseint () and integer.valueof () is that the Integer.parseint () method returns the base data type int and valueof () returns the Java.lang.Integer object. Java program, using the Integer.parseint () method to convert a string to an integral type:
public class Stringtointeger
{public
static void Main (string[] args)
{
String s = ' 2015 ';
int i = Integer.parseint (s);
System.out.println (i); output:2015
}
}
Java program, using the Integer.valueof () method to convert a string to an integral type:
public class Stringtointeger
{public
static void Main (string[] args)
{
String s = ' 2015 ';
int i = integer.valueof (s);
System.out.println (i); output:2015
}
}
How to convert a string to an integral type in Java
You also often need to do the opposite of the conversion, the integral type into a string. Java also provides a couple of methods. One is the integer.tostring () method and the other is the String.valueof () method. Both methods return the string form of the given integer. Java program, using the Integer.tostring () method to convert an integer to a string:
public class integertostring
{public
static void Main (string[] args)
{
int i = 2015;
String s = integer.tostring (i);
System.out.println (s); output:2015
}
}
Java program, using the String.valueof () method to convert an integer to a string:
public class integertostring
{public
static void Main (string[] args)
{
int i = 2015;
String s = string.valueof (i);
System.out.println (s); output:2015
}
}
Original link: String to integer and integer to String conversion in Java