DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Exploring Exciting New Features in Java 17 With Examples
  • Build a Java Microservice With AuraDB Free
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • High-Performance Java Serialization to Different Formats

Trending

  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  • AI Meets Vector Databases: Redefining Data Retrieval in the Age of Intelligence
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  1. DZone
  2. Data Engineering
  3. Data
  4. Data Type Conversions in Java

Data Type Conversions in Java

A brief guide to popular data type conversions in Java.

By 
Atta Shah user avatar
Atta Shah
·
Oct. 25, 22 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.0K Views

Join the DZone community and get the full member experience.

Join For Free

Unlike PHP or JavaScript, Java is a strongly typed programming language. It essentially means that each variable must be declared with a pre-defined data type that can not be changed afterwards. 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 String to int conversion: Integer.parseInt() which returns a primitive int and Integer.valueOf() which return an Integer object.

Java
 
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 int, we can convert a String into a primitive long value using Long.parseLong() or an object Long via Long.valueOf() method.

Java
 
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 value using Float.parseFloat() method. Float.valueOf() method can be used to convert a String into a Float object.

Java
 
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 the same but are different in the way that they store the value. 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 value using Double.parseDouble() method. Similarly, Double.valueOf() converts a String into a Double object.

Java
 
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 the String does not contain a parsable value during int, float, or double conversion, a NumberFormatException is thrown.

Java
 
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 value using Boolean.parseBoolean method. For conversion to Boolean object, you can use Boolean.valueOf() method.

Java
 
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 into a Date object
  • format() - It converts the Date object into a String value

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

Java
 
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 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 JavaDoc.

Letter Description Examples
y Year 2019, 19
M Month in year March, Mar, 03, 3
d Day in month 1-31
E Date name in a week Friday-Sunday
a Am/pm marker AM, PM
H Hour in day 0-23
h An 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:

Plain Text
 
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)


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:

Java
 
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:

Shell
 
Sunday, March 10, 2019 20:01:22.417 +0500


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:

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


Here is an example to convert a date object into an ISO 8601 equivalent string in Java:

Shell
 
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 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 MIT license.

Conclusion

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

Data (computing) Java (programming language) Strings Data Types

Published at DZone with permission of Atta Shah. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Exciting New Features in Java 17 With Examples
  • Build a Java Microservice With AuraDB Free
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
  • High-Performance Java Serialization to Different Formats

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!