Converting Between Strings and Other Data Types in Java


Illustration for Converting Between Strings and Other Data Types in Java
By Last updated:

String conversion is a daily task for Java developers β€” whether reading user input, formatting values for display, or storing data. Java provides robust APIs for converting strings to/from primitives, objects, arrays, and more.

This tutorial explores every key conversion between String and other data types in Java, helping you write safer, more efficient, and more readable code.


πŸ”„ Why String Conversion Matters

  • Reading from user input (Strings) and converting to numbers or booleans
  • Serializing objects for logging, networking, or persistence
  • Formatting output for reports or UIs

πŸ”’ String ↔ Integer

String to int

int num = Integer.parseInt("42");

int to String

String str = String.valueOf(42); // or Integer.toString(42)

πŸ”£ String ↔ Float / Double

String to float/double

float f = Float.parseFloat("3.14");
double d = Double.parseDouble("3.14159");

float/double to String

String s1 = String.valueOf(3.14f);
String s2 = Double.toString(3.14159);

πŸ” String ↔ Boolean

String to boolean

boolean b = Boolean.parseBoolean("true"); // case-insensitive

boolean to String

String str = Boolean.toString(true);

πŸ”€ String ↔ Char

char to String

char c = 'A';
String s = Character.toString(c);

String to char

char first = "Java".charAt(0);

⚠️ Ensure the string is not empty before calling charAt.


πŸ“š String ↔ Arrays

String to char array

char[] chars = "hello".toCharArray();

char array to String

String s = new String(new char[]{'J', 'a', 'v', 'a'});

String to String array (splitting)

String[] words = "one,two,three".split(",");

🧱 String ↔ Objects

Object to String

String s = String.valueOf(new Date());

Java calls the object's toString() method.

String to Object (via parsing or custom logic)

int age = Integer.parseInt("30"); // Wrapper classes

Or use libraries like Jackson/Gson for object deserialization from JSON/XML.


πŸ•’ String ↔ Date/Time

String to LocalDate

LocalDate date = LocalDate.parse("2025-08-07");

LocalDate to String

String s = date.toString(); // ISO format

Custom Format

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = LocalDate.parse("07-08-2025", fmt);

🧠 Performance and Safety Considerations

  • Always validate input before parsing (e.g., try-catch for NumberFormatException)
  • Use String.valueOf() over concatenation when performance matters
  • Prefer toString() overrides for custom object conversion

πŸ”„ Refactoring Example

❌ Clumsy Conversion

String s = "" + 123; // works but not readable

βœ… Clean Alternative

String s = String.valueOf(123);

πŸ“Œ What's New in Java?

Java 8+

  • Optional.map(Object::toString)
  • LocalDate, DateTimeFormatter

Java 11

  • String.repeat(), isBlank()

Java 21

  • String Templates (Preview) β€” improves conversion readability
String name = "Alice";
String msg = STR."Hello, \{name}";

βœ… Best Practices

  • Use valueOf() or toString() for primitives and objects
  • Always handle parse exceptions gracefully
  • Prefer formatting APIs (String.format, DateTimeFormatter) for dates and decimals
  • Validate input before converting strings to other types

πŸ”š Conclusion and Key Takeaways

  • Java offers simple, efficient ways to convert between String and other types.
  • Always use appropriate APIs (parseXxx(), valueOf(), toString()) for clarity and safety.
  • Choose formatters when dealing with locale-sensitive or custom-formatted data.

❓ FAQ

1. What’s the difference between parseInt() and valueOf()?

  • parseInt() returns an int; valueOf() returns an Integer (wrapper object).

2. Can I convert a String to a char?

Yes β€” use charAt(index).

3. How to convert boolean to String?

Use String.valueOf(boolean) or Boolean.toString().

4. What happens if I parse a non-numeric string?

A NumberFormatException is thrown.

5. Can I convert String to Enum?

Yes β€” use Enum.valueOf(MyEnum.class, str).

6. How to serialize an object to string?

Use .toString() or libraries like Jackson (JSON).

7. Is String.valueOf(null) safe?

Yes β€” it returns "null" string.

8. How to convert String to float?

Use Float.parseFloat("3.14").

9. How to parse date strings?

Use LocalDate.parse() or DateTimeFormatter.

10. Is String.valueOf(obj) better than obj.toString()?

Yes β€” it handles null safely.

πŸ“– Part of a Series

This tutorial is part of our Java Strings . Explore the full guide for related topics, explanations, and best practices.

β†’ View all tutorials in this series