The Integer class serves two purposes.
String s = "12345"; int x = Integer.parseInt(s);Note that this method can throw a NumberFormatException if the string does not represent an integer. The string is not allows to contain an leading or trailing blanks. You can use the trim method from the String class to eliminate any leading or trailing white space:
String s = " 12345 \n"; int x = Integer.parseInt(s.trim());
The Integer class also contains two important constants:
MAX_VALUE and MIN_VALUE.
System.out.println("The largest possible int in Java is "+Integer.MAX_INT); System.out.println("The smallest possible int in Java is "+Integer.MIN_INT);The values of these are 231-1 and -231.
The other use of the Integer class is to create an object that presents a single integer.
int x = 5; int y = 6; Integer x1 = new Integer(x); Integer y1 = new Integer(y); System.out.println("x = "+x+" and y = "+y); System.out.println("x1 = "+x1.intValue()+ and y1 = "+y.intValue()); x = y; System.out.println("x = "+x+" and y = "+y); System.out.println("x1 = "+x1.intValue()+ and y1 = "+y.intValue());This produces the following output:
x = 5 and y = 6 x1 = 5 and y1 = 6 x = 6 and y = 6 x1 = 5 and y1 = 6There are no methods for changing the value of an Integer object once it has bee created. Other way of saying this is that Integers are immutable.
The Integer class can be used to create an ArrayList containing integers. Recall that you cannot have an ArrayList of primitives, only of objects.
Example: Create an ArrayList and add 100 randomly generated Integer objects to it.
Random rand = new Random( ); ArrayList<Integer> values = new ArrayList<Integer>( ); for (int i = 0; i < 100; i++) values.add(rand.nextInt( ));This example shows a special feature of the wrapper classes referred to as auto boxing.
Java can also do auto unboxing. It is not recommended that you use the auto boxing or unboxing features.
The most useful method of the Double class is the parseDouble method:
String s = "123.456"; double x = Double.parseDouble(s);The parseDouble method can throw a NumberFormatException.
The Character class has a number of useful static methods: