Java is a strongly typed programming language, unlike PHP or JavaScript. It essentially means that each variable must be declared with a pre-defined data type that can not be changed afterward.
In Java, the process of converting a value of one data type (int
, long
, float
, double
, etc.) to another data type is known as type conversion or typecasting.
There are two main types of type conversions in Java:
- Widening Type Conversion
- Narrowing Type Conversion
Widening Type Conversion
When you assign a value of one data type to another, if they are compatible, Java automatically converts one data type to another data type. Such a conversion is known as widening or automatic type conversion.
Widening type conversion happens when:
- Both data types are compatible.
- We assign a lower data type (having a smaller size) to a higher data type (having a larger size).
// Declare integer variable
int num = 20;
// Convert integer to long (Widening Conversion)
long longNum = num;
// Convert long to float (Widening Conversion)
float floatNum = longNum;
// Convert float to double (Widening Conversion)
double doubleNum = floatNum;
System.out.println("Integer value: " + num);
System.out.println("Long value: " + longNum);
System.out.println("Float value: " + floatNum);
System.out.println("Double value: " + doubleNum);
// Integer value: 20
// Long value: 20
// Float value: 20.0
// Double value: 20.0
In the above example, we assigned an int
variable to long
, a long
variable to float
, and a float
variable to a double
variable without explicit typecasting.
It happened due to widening type conversion where Java automatically converts a value to another data type before assigning it to a variable of a higher data type. Hence, there is no loss of data.
Narrowing Type Conversion
In narrowing or explicit type conversion, we manually convert one data type into another data type in Java using the parenthesis.
This is useful when you want to assign a higher data type value to a small data type variable.
// Declare a double variable
double num = 20.2;
// Convert double to float (Narrowing Conversion)
float floatNum = (float) num;
// Convert float to long (Narrowing Conversion)
long longNum = (long) floatNum;
// Convert long to integer (Narrowing Conversion)
int intNum = (int) longNum;
System.out.println("Double value: " + num);
System.out.println("Float value: " + floatNum);
System.out.println("Long value: " + longNum);
System.out.println("Integer value: " + intNum);
// Double value: 20.2
// Float value: 20.2
// Long value: 20
// Integer value: 20
In the above example, we assign a float
type variable named floatNum
to a long
type variable named longNum
:
long longNum = (long) floatNum;
Here, the long
keyword in parenthesis indicates that the floatNum
variable is converted into a long
variable. Since we are assigning a higher data type (having a larger size) variable to a lower data type (having a smaller size) variable, there is a loss of data (20.2
to 20
).
This is why narrowing type conversion does not happen automatically.
Other Type Conversions
In Java, there are 13 types of type conversion. Let us see examples of other types of conversions.
Type conversion from string to integer
There are two methods available for String
to int
conversion: Integer.parseInt()
returns a primitive int
, and Integer.valueOf()
returns an Integer
object.
String str = "1050";
int inum = Integer.parseInt(str); // return primitive
System.out.println(inum);
Integer onum = Integer.valueOf(str); // return object
System.out.println(onum);
Read this guide to learn more ways to convert a string to an integer in Java.
Type conversion from string to long
Similar to int
, we can convert a String
into a primitive long
value using Long.parseLong()
or an object Long
using the Long.valueOf()
method.
String longStr = "1456755";
long ilong = Long.parseLong(longStr); // return primitive
System.out.println(ilong);
Long olong = Long.valueOf(longStr); // return object
System.out.println(olong);
Type conversion from string to float
A String
can be converted to a primitive float
value using the Float.parseFloat()
method. The Float.valueOf()
method converts a String
into a Float
object.
String floatStr = "49.78";
float ifloat = Float.parseFloat(floatStr); // return primitive
System.out.println(ifloat);
Float ofloat = Float.valueOf(floatStr); // return object
System.out.println(ofloat);
Type conversion from string to double
A String
value can be converted to a double
value using the Double.parseDouble()
method. Similarly, Double.valueOf()
converts a String
into a Double
object.
String doubleStr = "99.378";
double idouble = Double.parseDouble(doubleStr); // return primitive
System.out.println(idouble);
Double odouble = Double.valueOf(doubleStr); // return object
System.out.println(odouble);
Both
double
andfloat
data types may look the same, but they store the value differently. Afloat
is a single precision (32-bit or 4-bytes) floating point data type, whereas adouble
is a double precision (64-bit or 8-bytes) floating point data type.
If the String
does not contain a parsable value during int
, float
, or double
conversion, a NumberFormatException
is thrown.
try {
String exeStr = "14c";
int exeInt = Integer.parseInt(exeStr);
System.out.println(exeInt);
} catch (NumberFormatException ex) {
System.out.println(ex);
}
// java.lang.NumberFormatException: For input string: "14c"
Type conversion from string to boolean
A String
value can be converted to a primitive boolean
value using the Boolean.parseBoolean()
method. For string conversion to a Boolean
object, use the Boolean.valueOf()
method.
String trueStr = "true";
String falseStr = "false";
String randomStr = "java";
System.out.println(Boolean.parseBoolean(trueStr)); // true
System.out.println(Boolean.valueOf(falseStr)); // false
System.out.println(Boolean.parseBoolean(randomStr)); // false
Type conversion from string to date
Java provides a SimpleDateFormat
class for formatting and parsing dates. It has the following two methods:
parse()
— It converts aString
value into aDate
object.format()
— It converts theDate
object into aString
value.
While creating an instance of the SimpleDateFormat
classes, you need to pass the date and time pattern that tells how it should parse or format the dates.
String dateStr = "10/03/2022";
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = format.parse(dateStr);
System.out.println(dateObj);
In the example above, I used the dd/MM/yyyy
pattern to parse the 10/03/2022
string. dd
means two digits for the day, MM
means two digits for the month, and yyyy
means 4 digits for the year.
Below is a list of the most common date and time patterns used in SimpleDateFormat
. For the complete list, please refer to the official documentation.
Letter | Description | Examples |
---|---|---|
y | Year | 2022, 22 |
M | Month in year | March, Mar, 03, 3 |
d | Day in month | 1-31 |
E | Date name in week | Friday-Sunday |
a | Am/pm marker | AM, PM |
H | Hour in day | 0-23 |
h | Hour in am/pm | 1-12 |
m | Minute in hour | 0-59 |
s | Second in minute | 0-59 |
S | Millisecond in second | 0-999 |
z | General timezone | Central European Time, PST, GMT +05:00 |
Following are some pattern examples, with examples of how each pattern would parse a date or vice versa:
yyyy/MM/dd <--> (2022/03/09)
dd-MM-YYYY <--> (10-03-2022)
dd-MMM-yy <--> (13-Feb-22)
EEE, MMMM dd, yyyy <--> (Fri, March 09, 2022)
yyyy-MM-dd HH:mm:ss <--> (2022-02-28 16:45:23)
hh:mm:ss a <--> (11:23:36 PM)
yyyy-MM-dd HH:mm:ss.SSS Z <--> (2022-01-31 21:05:46.555 +0500)
Read this article to learn more about string-to-date conversion in Java.
Type conversion from date to string
As we discussed above, SimpleDateFormat
also supports the formatting of dates into strings. Here is an example that formats the date into a string:
Date date = Calendar.getInstance().getTime(); // OR new Date()
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, MMMM dd, yyyy HH:mm:ss.SSS Z");
String formatStr = dateFormat.format(date);
System.out.println(formatStr);
The above code snippet will print the following depending on your location:
Sunday, March 10, 2022 20:01:22.417 +0500
Type conversion from date to ISO-8601 string
ISO-8601 is an international standard that covers the exchange of date- and time-related data. There are several ways to express the date and time in ISO format:
2022-03-30T14:22:15+05:00
2022-03-30T09:22:15Z
20220330T092215Z
Here is an example that converts a date object into an ISO-8601 equivalent string in Java:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
isoFormat.setTimeZone(timeZone);
String isoFormatStr = isoFormat.format(new Date());
System.out.println(isoFormatStr);
Following are the date and time patterns for ISO format:
Pattern | ISO Date Format |
---|---|
yyyy-MM-dd'T'HH:mm:ssXXX | 2022-03-30T14:22:15+05:00 |
yyyy-MM-dd'T'HH:mm:ss'Z' | 2022-03-30T09:22:15Z |
yyyyMMdd'T'HHmmss'Z' | 20220330T092215Z |
Read this article to learn more about data-to-string conversion in Java.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.