Tuesday, 14 May 2013

Java some common type conversions

We often come across situations where data needs to be converted from one type to other and back again..or some other consecutive conversions.

However it is quite easy in case of java. This article will  be helpful for the beginners.

Conversions:

int to String  -  just add an extra empty string

int i = 5;
String str = "" + i ;


String to int   -  use the function parseInt( )

String str = "123" ;
int i = Integer.parseInt( str ) ;

char to String  -  just add an empty string

char c = 'b';
String str = "" + c ;

String to char - use function charAt()

String str = 's' ;
char c = str.charAt( s) ;

int to Double -  conversion is automatic

int i = 345 ;
Double d = i ;

Double to int -  add cast to double

Double d = 347 ;
int i = ( Double) d ;

Other conversions can be inferred using the ideas above since those are no different ;)


 

No comments:

Post a Comment