Converting between Data Types

Java converts a smaller number type to a larger one for you; anything else you convert yourself, with a cast for numbers or a parse method such as Integer.parseInt for text.

Apprentice · Java · Updated

By

Data conversion is important when performing arithmetic calculations. Many numeric conversions can happen automatically, and Java will make the conversion before it executes the expression.

Automatic conversion only works when a smaller data type fits into a larger one.

Example

String name = "Gary";
int age = 27;

// " is " is text, so age is converted to a string
// and the strings are joined
System.out.println(name + " is " + age); // prints Gary is 27
System.out.println();

int gallonsInFishTank = 55;
long gallonsInLake = 3000000000L;

// Because a long is bigger than an int, gallonsInFishTank is first
// converted to a long, and then the arithmetic is performed
long totalGallons = gallonsInFishTank + gallonsInLake;
System.out.println(totalGallons); // prints 3000000055

With numeric data types, a smaller data type will always be able to fit into a larger type.

  • byte into short
  • short into int
  • int into long
  • long into float
  • float into double

But the reverse is not true. A long cannot implicitly be converted to an int, even if the value of the long is small enough.

long bigAge = 18;

// The following line is illegal
// because Java cannot determine if the value of bigAge
// will always be small enough to fit inside an integer memory space
int age = bigAge;

If you know that the value of bigAge is small enough to be stored as an integer, you can convert the memory to store an int instead of long.

Type Casting

Type casting means that you specify what data type you want to use when working with a variable.

long bigAge = 18;

// by putting (int) in front of bigAge
// We specify that 18 should be cast as an int.
int age = (int)bigAge;

System.out.println(age);
System.out.println();

Type casting only works correctly if the value stored in the variable bigAge is small enough to be treated as an int.

Another Example

In the following example, the value of the variable manyGallons is 3 billion, but an int data type can only store a value up to 2,147,483,647 (2.14 billion). When this data type conversion happens, we will receive an unexpected result.

Java will subtract the maximum integer value from 3,000,000,000 and then roll over to the minimum integer value (-2,147,483,648). Finally, it adds the remaining numbers.

// Using another example:
long manyGallons = 3000000000L;
int gallons = (int)manyGallons; // line of our conversion logic error
System.out.println(gallons); // prints -1294967296
System.out.println();

Converting Strings to Numbers

We frequently get data as a string, but we need to convert it to a number in order to use it to perform calculations.

// arithmetic cannot be performed on String datatypes
String age = "25";
age += 1;
System.out.println(age); // this prints 251

The String must first be converted to a numeric datatype.

Each primitive datatype has a wrapper class that allows us to perform String-to-primitive conversion.

Type Method that converts a String to it
int Integer.parseInt()
long Long.parseLong()
float Float.parseFloat()
double Double.parseDouble()
boolean Boolean.parseBoolean()
String ageValue = "25";
int age = Integer.parseInt(ageValue);
age += 1;
System.out.println(age); // prints 26

String priceValue = "15.50";
double price = Double.parseDouble(priceValue);
double discount = price * .1;
System.out.println("The 10% discount is " + discount);

Do it: total an order that arrived as text

Build-It Pizzeria's order form sends every value as text, even the numbers. Before the program can work out what an order costs, it has to turn that text into numbers.

The program starts with two values from the form:

  • quantityText: how many pizzas were ordered, as text: "3".
  • priceText: the price of one pizza, as text: "12.50".

Worked through:

Step From To
Turn the quantity into an int "3" 3
Turn the price into a double "12.50" 12.5
Multiply them 3 × 12.5 37.5

A double doesn't keep zeros at the end, so 12.50 prints as 12.5. main() then prints exactly:

3 pizzas at 12.5 each cost 37.5

Your job: fill in the three variables the starter has set to 0.

  • quantity is an int: the number in quantityText.
  • price is a double: the number in priceText.
  • total is a double: quantity times price.
  • Work each one out from the variables above it; don't type 3, 12.5 or 37.5 yourself.
  • Leave quantityText, priceText and main() as they are.

The box holds a short Java file: the variables and a main() method with nothing around them. Since Java 25, a small program can be written this way, and main() runs when the program starts.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets