How to construct an Integer:
- public Integer(int value)
- public Integer(String s)
Note: this string must be composed of numeric characters
The code example is as follows:
public class IntegerDemo { public static void main(String[] args) { //Mode 1 int i = 100; Integer i1 = new Integer(i); System.out.println("i1:"+i1); //Mode 2 String s = "100"; //NumberFormatException //String s = "abc"; Integer ii = new Integer(s); System.out.println("ii:"+ii); } }
Operation result:
i1:100
ii:100
Conversion between int type and String type:
The methods of int - > string are as follows:
- Method 1: String splicing
- Method 2: String.valueOf() method of String
- Mode 3: int > integer > string
- Mode 4: toString method of Integer
The demo code is as follows:
public class IntegerDemo { public static void main(String[] args) { //int --- String int number = 100; //Method 1 string splicing String s1 = "" + number; System.out.println("s1:"+s1); //Mode two String s2 = String.valueOf(number); System.out.println("s2:"+s2); //Mode three //int -- Integer -- String Integer i = new Integer(number); String s3 = i.toString(); System.out.println("s3:"+s3); //Mode four //public static String toString(int i) String s4 = Integer.toString(number); System.out.println("s4:"+s4); System.out.println("--------------------"); } }
Operation result:
s1:100
s2:100
s3:100
s4:100
String - > int can be used in the following ways:
- Method 1: String > integer > int, and then public int intValue()
- Method 2: public static int parseInt(String s)
The sample code is as follows:
public class IntegerDemo { public static void main(String[] args) { //String -- int String s = "100"; //One way //String -- Integer -- int Integer ii = new Integer(s); //public int intValue() int x = ii.intValue(); System.out.println("x:"+x); //Mode two //public static int parseInt(String s) int y = Integer.parseInt(s); System.out.println("y:"+y); } }
Operation result:
x:100
y:100