• Post Reply Bookmark Topic Watch Topic
  • New Topic

String Conversion  RSS feed

 
chinna kumar
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

i have 2 variables.

int i=10;
String st= new String();

how to assign i to String.

i tried in this way..
st=(String)i;
but it thows error.. itried with toString().. also.


any clue.. please...


Chinna
 
Bajji Pat
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
U can do it like this

st = ""+i;
 
Neeraj Dheer
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can also do it this way:



perhaps this is clearer?
 
Shyam Prasad Murarka
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Readers,
Or you could do it this way also:
 
Ranga Kalidindi
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chinna,

To just let you know why you got this error :

In Java, basically we have two 'types' of values/variables.
- basic data types (eg: int, float, char, byte, ..etc)
- objects (eg: String, Integer, ..etc)

We cannot convert a basic data type into an object using type-casting.
Type-casting helps us to convert from
- one basic data type to another basic data type
- one object to another object depending on the inheritance structure

Java provided us with 'wrapper' classes for almost all basic types so that we can represent basic data types as objects. You can use these classes to convert your 'int' into a 'String' object. That is why, many of the replies that you received so far also use this technique.

String st = Integer.toString(i);

string = String.valueOf(i);

If you understand the features of a 'String' in java, the output when any basic data type concatenated with a String object is a String. Even this technique of String concatenation is simple:

st = ""+i;


Thanks,
Ranga
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!