Java Data Type Conversions

by Ron Zucker

data type3
range3
string to object
string to type1
object to type2
type to object (constructors)
type to string
boolean
true or false
valueOf( s )
Boolean( s)
getBoolean( s )
booleanValue()
Boolean(boolean_value)
valueOf(type)
char
'\u0000' - '\uFFFF' ISO Unicode character set
Character(charAt(int))
charAt(int)
charValue()
Character(char value)
byte
-128 - 127

 

parseByte(s)*
byteValue()*

 

short
-32768 - 32767
 
parseShort(s)*
shortValue()*

 

int
-2,147,483,648 -
2,147,483,647
valueOf( s )
Integer( s)
parseInt( s)
intValue()
Integer(int value)
long
-9,223,372,036,854,775,808 -
9,223,372,036,854,775,807
valueOf( s )
Long( s)
parseLong( s)
longValue()
Long(long value)
float
-3.40292347+E38-3.40292347+E38
valueOf( s )
Float( s)
parseFloat(s)*
floatValue()
Float(float value)
double
-1.79769313486231570E308-
1.79769313486231570E308
valueOf( s ) Double( s )
parseDouble(s)*
doubleValue()
Double(double value)
1. the parseType(s) methods are static methods of their respective wrapper classes. The ones denoted by the asterisk are new to JDK1.2.
NOTE: Primitive data types must be cast using the format (cast type)var if the data is "demoted" to a lower precision.
Example:
float floatvar;
double doublevar;
floatvar= (float)doublevar;
this will allow the doublevar to be demoted from type double to a less precisetype float
2.Numerical objects of one class maybe converted to other alternate types by substituting in the converted type name in lower case succeeded by Value.
Examples:
Doubleobj.intValue()
will convert a Double object to an int type
Doubleobj.floatValue()
will convert a Double object to a float type
Conversions can be quite lengthy. Consider the following code which converts a TextField entry (which is a string) and converts it to a primitive float datatype:
val1=Float.valueOf(vals[0].getText()).floatValue();
where vals[0] is an object of type TextField, and val1 is of primitive type float. The following steps indicate how the conversion takes place:
1.       vals[0].getText() method returns the string from the textbox assigned to object vals[0]
2.       Float.valueOf(vals[0].getText()) converts the string to an object Float
3.       .floatValue() converts the Float object to a primitive type float.

All of this was necesssary because there are no string to type methods for type float.

3. Java How to Program, Dietel & Dietel, Prentice Hall, 1997, page 95


Additions, corrections, comments please email to rzucker@unf.edu(click to send mail)