data type conversion in java

Unlike PHP or JavaScript, Java is a strongly typed programming language. This essentially means that each variable must be declared with a pre-defined data type that cannot be changed later. There are two data types in Java:

  • Primitive data types – int, double, float, byte, long, boolean, etc.
  • Reference data types – integer, double, float, date, string, object, etc.

In this tutorial, we will focus on type conversion for primitive data types.

string to int

There are two methods available for this String To int Conversions: Integer.parseInt() which returns a primitive int And Integer.valueOf() which returns a Integer Thing.

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);

string to long

similar to intwe can convert a String in a primitive long use of value Long.parseLong() or an object Long Via Long.valueOf() way.

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);

string to float

a String can be converted to primitive float use of value Float.parseFloat() way. Float.valueOf() Using method a. can be done to convert String In Float Thing.

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);

string to double

double And float Data types may look similar but differ in the way that they store values. float is a single precision (32-bit or 4 bytes) floating point data type whereas double is a double precision (64-bit or 8-bytes) floating point.

a String value can be converted to double use of value Double.parseDouble() way. Similarly, Double.valueOf() converts String In Double Thing.

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);

NumberFormatException

If String does not contain a passable value during int, floateither 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.getMessage());
}

string to boolean

a String value can be converted to primitive boolean use of value Boolean.parseBoolean way. for conversion Boolean object, you can use Boolean.valueOf() way.

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

string to date

java provides SimpleDateFormat Class for formatting and parsing dates. It has the following two important methods:

  • parse() – it converts a String value in a Date Thing
  • format() – it converts Date object in one String value

when creating an instance of SimpleDateFormat classes, you need to pass a date and time pattern that describes how the instance should parse or format the dates.

String dateStr = "10/03/2019";

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date dateObj = format.parse(dateStr);
System.out.println(dateObj);

In the example above, I used dd/MM/yyyy pattern to parse 10/03/2019 string. dd means two digits for the day, MM means two digits for the month and yyyy Means 4 points for the year. Below is a list of the most common date and time patterns that are used. SimpleDateFormat, For a complete list, please refer to the official JavaDoc.

Letter description Example
You year 2019, 19
M month in year march, march, 03, 3
D days in the month 1-31
I date in a week Friday Sunday
One am/pm marker am PM
h hour in day 0-23
h one hour in the am/pm 1-12
M minutes to hours 0-59
s second in minute 0-59
s milliseconds to seconds 0-999
jade common timezone Central European Time, PST, GMT +05:00

The following are some pattern examples, with examples of how each pattern would parse a date or vice versa:

yyyy/MM/dd  <--> (2019/03/09)

dd-MM-YYYY  <-->  (10-03-2019)

dd-MMM-yy  <-->  (13-Feb-19)

EEE, MMMM dd, yyy  <--> (Fri, March 09, 2019)

yyyy-MM-dd HH:mm:ss <--> (2019-02-28 16:45:23)

hh:mm:ss a <--> (11:23:36 PM)

yyyy-MM-dd HH:mm:ss.SSS Z <--> (2019-01-31 21:05:46.555 +0500)

string date

As we discussed above, SimpleDateFormat Also supports formatting of dates into strings. Here’s an example that formats a 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, 2019 20:01:22.417 +0500

ISO 8601 date string

ISO 8601 is an international standard that covers the exchange of data relating to dates and times. There are several ways to express a date and time in ISO format:

2019-03-30T14:22:15+05:00
2019-03-30T09:22:15Z
20190330T092215Z

Here’s an example to convert a Date object to 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);

The following are the date and time patterns for the ISO format:

pattern iso date format
yyyy-MM-dd’T’HH:mm:ssXXX 2019-03-30T14:22:15+05:00
yyyy-MM-dd’T’HH:mm:ss’Z’ 2019-03-30T09:22:15Z
yyyyMMdd’T’HHmmss’Z’ 20190330T092215Z

source code: Download the complete source code from GitHub, available under the MIT license.

conclusion

Data type conversions are very common for a developer. Most of these conversions are trivial and are known to an experienced programmer. However, string-to-date conversion is a bit tricky, especially for beginners. If the pattern is not specified correctly, you may encounter errors. But if you spend some time remembering these patterns, it can save a lot of time figuring out why a certain conversion isn’t compiling or executing.

Leave a Comment