Java Conversions: Understanding valueOf(), parseInt(), and toString()

For years, I found myself second-guessing which method to use when converting between primitives, wrapper classes, and strings in Java. Do I use valueOf()
here? What about parseInt()
? When should I use toString()
?
If that confusion sounds familiar, hopefully this guide will clean it up.
🔹 Converting to a Wrapper Class? → Use valueOf()
The first thing to know is: valueOf()
is not some universal magic converter.
It works only when you're converting to a wrapper of a specific type, like Integer
, Double
, Boolean
, etc. And it accepts:
a primitive of the same type (e.g.,
int
forInteger
)or a String that represents a value of that type (e.g.,
"123"
forInteger
)
Examples:
javaCopyEditInteger i1 = Integer.valueOf(100); // primitive int → Integer
Integer i2 = Integer.valueOf("100"); // String → Integer
Boolean b = Boolean.valueOf("true"); // String → Boolean
This is where most people stop and assume valueOf()
works for converting anything into anything — but that's wrong.
🔸 Converting One Wrapper to Another? → You Must Unbox and Rebox
Let’s say you want to convert an Integer
to a Double
.
Can you do this?
javaCopyEditInteger i = 10;
Double d = Double.valueOf(i); // ❌ Won’t compile
Nope. Double.valueOf()
does not accept an Integer
— it expects a double
or a String
.
✅ Correct Way:
javaCopyEditDouble d = Double.valueOf(i.doubleValue()); // Integer → double → Double
This is key: Java doesn't auto-convert between different wrapper types. You have to extract the primitive, convert it if needed, and then wrap it again.
🔹 Converting to a Primitive? → Use parseXxx()
(Always)
If your end goal is a primitive (int
, double
, boolean
, etc.), the answer is always the parseXxx()
methods:
javaCopyEditint i = Integer.parseInt("123"); // String → int
double d = Double.parseDouble("45.67"); // String → double
boolean b = Boolean.parseBoolean("true"); // String → boolean
That’s it. Use parse
when you want to strip the object and get a raw value.
Don't overthink it.
🔹 Converting to a String?
This one also gets unnecessarily confusing. Here's the rule:
👉 If you’re starting from a primitive — use String.valueOf(...)
:
javaCopyEditString s = String.valueOf(123); // int → String
String s2 = String.valueOf(false); // boolean → String
👉 If you're starting from a wrapper — you can:
javaCopyEditString s = Integer.valueOf(999).toString(); // Wrapper → String
Or if you want to keep things generic:
javaCopyEditString s = String.valueOf(Integer.valueOf(888)); // Still works
Subscribe to my newsletter
Read articles from Shailesh Patil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Shailesh Patil
Shailesh Patil
I'm a Java backend developer learning core concepts to deepen my understanding. Most resources were either too shallow or too overwhelming—so I started sharing my perspective to simplify the learning process. If you're on a similar path, I hope this helps you too.