Java Datatype Conversion
There will be many occasions when you will need to convert data from one type to another. Later, when we explore arrays, you will see that converting datatypes is a very common requirement in Java programming and something you will need to fully understand. In this lesson we will discuss two types of data conversion:
Numerical datatype conversion
Converting data to and from integers, floats and doubles
String datatype conversion
Converting data from strings to integers, floats and doubles
Numerical Datatype Conversion
In the lesson Datatypes and Variables you learnt about the three primary numerical datatypes, here’s a reminder of three of those datatypes and their properties:
int – Integer number: The integer datatype holds a single whole number – with no fractional parts. It occupies 4 bytes of memory and has a minimum value of – 2,147,483,648 and a maximum value of 2,147,483,647. An integer is generally used as the default data type for integral values unless there is a concern about memory (Integral means consisting of a whole number or an undivided quantity).
double – Decimal point number: The double datatype holds a single decimal point number and occupies 8 bytes of memory. It can store values from 1.7e−308 to 1.7e+038 which is sufficient for storing 15 decimal digits.
float – Floating point decimal number: The float datatype holds a large decimal point number and occupies 4 bytes of memory. It can can store fractional numbers from 3.4e−038 to 3.4e+038, sufficient for storing 6 to 7 decimal digits.
Each of these datatypes have some significant differences that may require their conversion to another datatype as your program progresses. For example, your program may use an integer to store the age of students enrolled on a course – this makes sense as we would normally consider our age to be a whole number like 21 years old or 34 years old. But, if our program was required to calculate the average age of students we may need a higher precision for that number, a number with a decimal point. In that case we would need to use a double or float as the datatype for the average age, so when performing the calculation we would need to convert each student age from an integer to a datatype with a fractional part before adding them together to calculate the average.
Converting a primitive datatype from type one to another is done in one of two ways where the type can be:
- a smaller type is promoted to a larger type
- a larger type is type cast to smaller type
Type Promotion
In this lesson we will focus on the three most common numeric datatypes: int, double and float. You know that int, float and double datatypes hold different types of numeric data:
- int: 4 bytes, large number that does not have a fractional part
- float: 4 bytes, large number that could have a fractional part
- double: 8 bytes, a very large number that could have a fractional part
Let’s create a variable and assign a value to each datatype for use later:
int numInt = 35; float numFloat = 10.21f; double numDouble = 44.543; System.out.println("numInt = " + numInt); System.out.println("numFloat = " + numFloat); System.out.println("numDouble = " + numDouble);
Type in the about code into you IDE, your output should be:
run: numInt = 35 numInt = 35 numInt2Float = 35.0 BUILD SUCCESSFUL (total time: 0 seconds)
With type promotion, a smaller type can be promoted to a larger type. So if target type is larger than the source type can be no data loss since there is more room in the target type. Starting with one of the smallest datatypes, a byte, we can map out the potential promotion route of datatypes:
byte -> short -> int -> long -> float -> double
So, for example, since a float is larger than an integer, we can promote an int to a float and no data will be lost. Type promotion is sometimes referred to as Implicit Type Casting since we imply rather than state the new datatype and the conversion occurs without specifying the target type, Java will promote the type automatically:
System.out.println("numInt = " + numInt); float numInt2Float = numInt; System.out.println("numInt = " + numInt); System.out.println("numInt2Float = " + numInt2Float);
Line 1 reminds us of the value of numInt. Line 2 creates a new float variable called numInt2Float and assigns the value of the integer variable numInt to it, essentially promoting the value from an int to a float. Line 3 confirms that the value of numInt has not changed, it is still an integer of value 35. Line 4 confirms that the value of numInt2Float is a promoted value of numInt – we know this because the value has a fractional part: 35.0.
Type in the above code into your IDE. Your output should be:
run: numInt = 35 numInt = 35 numInt2Float = 35.0 BUILD SUCCESSFUL (total time: 0 seconds)
The same type promotion can be performed on a variety of datatypes as long as you observe the rule that only a smaller type can be promoted to a larger type.
Type Casting
With type casting, sometimes referred to as Explicit Type Casting, we do specify the target datatype, and there is a risk of losing data since the target type can be smaller than the source type:
double -> float -> long -> int -> short -> byte
You recall we have an integer variable called numInt. To convert its value to a float using type casting we need to state the new datatype in brackets before the name of the variable we want to convert. The general syntax is:
(newDataType)variableName
So let’s see type casing in action by converting an integer to a float:
//This is the interger variable created earlier int numInt = 35; System.out.println("The value of numInt = " + numInt); //the syntax is (newDataType)variableName //so we need (float)numInt //let's print put the result: System.out.println("The value of numInt as a float = " + (float)numInt);
The output displays the value of numInt as an integer and a float:
run: The value of numInt = 35 The value of numInt as a float = 35.0 BUILD SUCCESSFUL (total time: 0 seconds)
Using the same general syntax we can convert other datatypes too. Let’s try a float to a double:
//This is the float variable created earlier float numFloat = 10.21f; System.out.println("The value of numFloat = " + numFloat); //the syntax is (newDataType)variableName //so we need (double)numFloat //let's print put the result: System.out.println("The value of numFloat as a double= " + (double)numFloat);
The output displays the value of numInt as an integer and a float:
run: The value of numInt = 35 The value of numInt as a float = 35.0 BUILD SUCCESSFUL (total time: 0 seconds)
So with type casting was can convert any numeric datatype to another, for example a float to a double:
double d = (double)f;
Or a double to an integer:
int i = (int)d;
The important this to remember with (explicit) type casting is that you may lose some data is the target type is smaller than the source type.
Converting Strings
String are very useful datatypes. They can store a lot of data and can contain practically any characters like numbers, letter, special character, etc. This makes them very useful when you need to store a lot of different types of data but can only use one datatype, like an array for example. However, if a number is stored as a string type it cannot be used like a number mathematically. You will need to covert these strings into a numerical datatype first. These can be converted into appropriate data type using the following methods:
- parseInt()
- parseFloat()
- parseDouble()
Let’s say we have a string that contains two characters, both are the character 9, styored in a variable stringNum:
String stringNum = "99"; System.out.println(stringNum);
The output should be:
run: 99 BUILD SUCCESSFUL (total time: 0 seconds)
Now, the output looks like 99 is a number, but we know that it is infarct a String, and as a string it cannot be manipulated mathematically. Let’s test this by adding 1 to the variable stringNum. If stringNum was a number the result of 99 + 1 would be 100:
System.out.println(stringNum + 1);
The output is:
run: 991 BUILD SUCCESSFUL (total time: 0 seconds)
This is not the sum of the numbers 99 + 1, but rather the concatenation of a string “99” and a numeric 1.
To convert this string into a numeric datatype we need to use an appropriate parse method. Let’s use the parseInt() method to convert this string to an integer, and let’s add 1 to the newly converted integer to conform that it is a number and not a string. The parseInt() method is from the Integer class, so we need to append the class name as suffix (note the capital I, all classes start with a capitol letter):
The output should be:
int intNum = Integer.parseInt(stringNum); System.out.println("intNum: " + intNum); System.out.println("intNum + 1: " + (intNum + 1));
run: intNum: 99 intNum + 1: 100 BUILD SUCCESSFUL (total time: 0 seconds)
We can see that the conversion was successful, the numbers 99 + 1 = 100.
The same rules apply to floats and doubles
- The parseFloat() method is from the Float class and will convert a string to a float
- The parseDouble() method is from the Double class and will convert a string to a double
Using the stringNum variable let’s use these method to convert a string to a double and float:
double doubleNum = Double.parseDouble(stringNum); System.out.println("doubleNum: " + doubleNum); float floatNum = Float.parseFloat(stringNum); System.out.println("floatNum: " + floatNum);
The output should be:
run: doubleNum: 99.0 floatNum: 99.0 BUILD SUCCESSFUL (total time: 0 seconds)
You might notice that the variables doubleNum and floatNum output the same value of 99.0. This confirms that both have been converted to floating point numbers since both have a fractional part (the .0).
What you have learnt
In this lesson you learnt what how to convert numerical datatypes using promotion (implicit) and type casting (explicit). You also learnt how to convert strings to numerical datatype using the parseInt(), parseDouble() and parseFloat() methods.