Data Type Conversion | Heaton Research

Data Type Conversion

Get the entire book!
Java for the Beginning Programmer

Earlier in this chapter we saw how you can create both string and numeric data types. Often you will need to convert between the two. Consider an example where you have a string that contains 1001.

String str = "1001";

Now you would like to add 5 to the string. If you use the following line of code, you might not get what you expect.

str = str + 5;

What would str now contain? Would it contain “1006”? No it would not! It would actually contain “10015”. This is because anything added to a string is concatenated. Which means it is simply tacked on to the end. To properly perform this operation you would have to convert str to an integer, perform the addition, then convert it back to a string. I will now show you how to perform this conversion. There are actually three conversion types that you will often do with numeric and string variables.

  • Convert a string to a numeric
  • Convert a numeric to string
  • Convert a numeric to a different numeric

I will begin by showing you how to convert a string to a numeric.

Converting String to Numeric

Converting a string to a numeric is a very common operation to perform. Anytime you read data from the user it always is given to you in string form. No matter if you are using a console application or one of the more advanced GUI, data always comes in string form. Often, you will need to convert this user input into numeric form so that you can properly process the data. The following lines of code would convert our string, containing “1001” into an integer.

String str = "1001";
int i = Integer.parseInt(str);

By using the function “Integer.parseInt” you pass in str as an argument and the function returns an integer. Now that “i” contains an integer you can easily add 5 to it as follows.

i = i + 5;

The variable “i” will now contain 1006.

You may be wondering what would happen if you pass an invalid number into Integer.parseInt. For example, what would happen if you passed in the string “Java”? You might be able to guess the answer from the last section. What happens when a method or function is given data that it cannot handle? An exception is thrown! In this case, an exception named NumberFormatException is thrown. In the case of NumberFormatException, Java does NOT require us to catch it.

However, if you do not catch it, any invalid number that you might encounter is going to cause your program to crash. Because of this you should catch the NumberFormatException, especially if you are reading user input. You should NEVER assume that your user will give you valid data! The following code would prompt the user for a number and display an error if they provide an invalid number.

try
{
// display a prompt to the user
  System.out.print("Please enter a number>");

// create a stream to read from the user
  BufferedReader userInput = new BufferedReader(
    new InputStreamReader(System.in));

// read a line of text from the user
  String str = userInput.readLine();

// attempt to convert the user's input into 
// an integer
  int i = Integer.parseInt(str);
}
catch(IOException e)
{
  System.out.println("An IO exception occured.");
}
catch(NumberFormatException e)
{
  System.out.println("Enter a valid number!!");
}

The above block of code brings together several concepts we have learned. First a BufferedReader stream is created to read the string from the user. Next, a line of input is read from the user and converted to an int. Finally the user’s input is converted into an integer.

Did you notice the catch blocks? There are two of them. Two catch blocks are required because two different exceptions can occur. First, the readLine function could throw an IOException. Secondly, the Integer.parseInt function could throw a NumberFormatException. When you have more than one exception type you are allowed to “stack” catch blocks like this.

Now that you have seen how to convert a string to an integer, you may be wondering about the other Java data types, such as short or double. You should be able to infer the correct function call from the data type. For example, to convert a double, you would use Double.parseDouble. Each of the function calls are summarized here.

  • byte: Byte.parseByte(str)
  • double: Double.parseDouble(str)
  • float: Float.parseFloat(str)
  • int: Integer.parseInt(str)
  • long: Long.parseLong(str)
  • short: Short.parseShort(str)

Important: The int type is inconsistent with the others. To convert to an int, you use Integer.parseInt, not Int.parseInt. Do not be confused by this, it is just an unfortunate inconsistency in the Java language.

Now that you have seen how to convert a string to a numeric, lets examine the opposite conversion.

Converting Numeric to String

Converting a numeric to a string is much easier than the reverse operation. You have already been converting numeric variables to strings, you just might not have been aware of it. Anytime you print out a variable with System.out.println, you are converting a numeric into a string.

int i = 1000;
System.out.println("The value of i is: " + i );

Here the value of “i” was converted to a string, attached to the end of the constant string and the result was printed out. So if you just want to convert to a string and not display the result, add to an empty constant string (“”) and assign the result to a string.

int i = 1001;
String str = "" + i;

Now “i”” has been converted to a string named str. This will work just as well for all of the numeric data types.

Converting Numeric to Numeric

Sometimes you may want to convert one numeric type to another numeric type. So long as the target numeric type is larger than the source numeric type, this is okay. For example, assigning an int into a long is fine.

long l;
int i;

i = 10;
l = i;

Because a long is larger than an int, this is fine. You would not lose data making such a copy. However, if you try to copy a long into an int, you will run into a problem.

long l;
int i;
l = 10;
i = l;

Now you will be given an error. You are trying to copy a long into an int. Of course we know that the number 10 would fit into the int just fine. However, Java makes no such distinction. If Java sees that the type on the left of an = is smaller than the type on the right, a compile error results.

If you really want to copy a long into an int you must tell Java that you really want to be doing this, and you do not mind that the result might not fit. You do this with a type-cast.

long l;
int i;
l = 10;
i = (int)l;

Now you are converting the “l” variable into an int before it is assigned to “i”. This will compile just fine. If you ever get an error converting from one numeric type to another just use a type-cast to convert the right side of the = to the correct type.

This same technique works on floating point numbers. You can also use it to strip the decimal places from a floating point number. For example, the following code would strip the decimal places from the double variable d.

double d;
d = 10.5;
d = (double)((int)d);
System.out.println("The value of d is " + d );

The above code would display 10. Do you see how this is happening? First the double variable d is converted to an int. This conversion causes d to lose all decimal places. The result is truncated, not rounded. But then, the result is converted back into a double, so that it can be assigned back into d.

Copyright 2005-2008 by Heaton Research, Inc.