File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Have a question about convert int to string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Have a question about convert int to string" Watch "Have a question about convert int to string" New topic

Have a question about convert int to string

chang nanny

Joined: Feb 15, 2004
Posts: 14
int x = 1;
String sx = (String)x;
The preceding code compile error.
Why can't use "(String)" to cast?
Thank you.
Ashok C. Mohan
Ranch Hand

Joined: Dec 03, 2003
Posts: 75
int is a primitive data type,whereas String is an object.A cast from a primitive to an object does not make sense.Inorder to perform conversions like this,java provides a wonderful set of classes called wrapper classes.The wrapper class objects wraps around primitives to make them behave similar to objects.The conversion you tried can be done like this....

Hope this helps...

SCJP 1.4
Do not dwell in the past, do not dream of the future, concentrate the mind on the present moment.
Brian Pipa
Ranch Hand

Joined: Sep 29, 2003
Posts: 299
This works too:


My Java Freeware:<br />MACCC - <a href="" target="_blank" rel="nofollow"></a><br />Nator - <a href="" target="_blank" rel="nofollow"></a>
Eddie Vanda
Ranch Hand

Joined: Mar 18, 2003
Posts: 281

The valueOf method in String can take any primitive value, no wrapper class required!

The nice thing about Standards is that there are so many to choose from!
Tom Boyce

Joined: Jul 03, 2003
Posts: 24
But the easiest way to convert an int to a String is:
int x = 1;
String sx = (x+"");
by concatenating any primitive with an empty string you cast it as a String
double y = 1.2;
String sy = (y+"");
Other casting examples:
public class Conversions
public static void main(String[] args)
String strQuantity = "5"; //simulating the customer has entered 5 into a text field
//to perform a calculation, string must be converted to an int.
int quantity = Integer.parseInt(strQuantity);
String strPrice = "25.5";
double price = Double.parseDouble(strPrice);
//perform a calculation
double total = quantity*price;
//convert total to a string
String strTotal=total+"";
Tom Boyce
I agree. Here's the link:
subject: Have a question about convert int to string
It's not a secret anymore!