CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Data

Data
Working with data types
Integer and Double classs

How to use the Integer and Double classes

  • The Integer and Double classes are known as wrapper classes since they can be used to construct Integer and Double objects that contain (wrap around) int and double values.
  • These classes can be useful when you need to pass an int or double value to a method that accepts only objects, not primitive data types.
  • These classes also provide static methods that you can use for converting values from these data types to strings and vice versa.
  • If the parseInt and parseDouble methods can't successfully parse the string, they will cause an error to occur. In Java terminology, this is known as throwing an exception.
  • Every primitive type has a wrapper class that works like the Integer and Double classes.

Constructors for the Integer and Double classes

Constructor Description
Integer(int) Constructs an Integer object from an int data type.
Double(double) Constructs a Double object from a double data type.

Two static methods of the Integer class

Method Description
parseInt(stringName) Attempts to convert the String object that's supplied as an argument to an int type. If successful, it returns the int value. If unsuccessful, it throws an exception.
toString(intName) Converts the int value that's supplied as an argument to a String object and returns that String object.

Two static methods of the Double class

Method Description
parseDouble(stringName) Attempts to convert the String object that's supplied as an argument to a double type. If successful, it returns the double value. If unsuccessful, it throws an exception.
toString(doubleName) Converts the double value that's supplied as an argument to a String object and returns that String object.

How to create Integer and Double objects

Integer quantityDoubleObject = new Integer(quantity);
Double priceDoubleObject = new Double(price);

How to use static methods to convert primitive types to String objects

String counterString = Integer.toString(counter);
String priceString = Double.toString(price);

How to use static methods to convert String objects to primitive types

int quantity = Integer.parseInt(quantityString);
double price = Double.parseDouble(priceString);

Previous | NumberFormat class | Math class | Integer and Double classs | Next