How to convert String to primitive type value?
Given the str reference which refers to an instance of String without leading and trailing white space:
- Convert String to int:
try {
int i = Integer.parseInt(str);
/* or */
Integer I = Integer.valueOf(str);
int i1 = I.intValue();
}
catch (NumberFormatException e){
;
}Here is another example for the string presents a hexdecimal string:
try {
int i = Integer.parseInt(str, 16 );
}
catch (NumberFormatException e){
;
}Note: Parses the string argument as a signed
integerin the radix specified by the second argument. The characters in the string must all be digits, of the specified radix (as determined by whetherCharacter.digit(char, int)returns a nonnegative value) except that the first character may be an ASCII minus sign'-'('\u002D') to indicate a negative value. The resultingbytevalue is returned. - Convert String to short:
try {
short s = Short.parseShort(str);
/* or */
Short S = Short.valueOf(str);
short s1 = S.shortValue();
}
catch (NumberFormatException e){
;
} - Convert String to byte:
try {
byte b = Byte.parseByte(str);
/* or */
Byte B = Byte.valueOf(str);
byte b1 = B.byteValue();
}
catch (NumberFormatException e){
;
} - Convert String to long:
try {
long l = Long.parseLong(str);
/* or */
Long L = Long.valueOf(str);
long l1 = L.longValue();
}
catch (NumberFormatException e){
;
} - Convert String to float:
try {
float f = Float.parseFloat(str);
float f1 = Float.valueOf(str).floatValue();
}
catch (NumberFormatException e){
;
} - Convert String to double:
try {
double d= Double.parseDouble(str);
double d1 = Double.valueOf(str).doubleValue();
}
catch (NumberFormatException e){
;
} - Convert String to boolean:
Boolean B = Boolean.valueOf(str);
boolean b= B.booleanValue();No exception needs to catch because the
Booleanreturned represents the valuetrueif the string argument is notnulland is equal, ignoring case, to the string"true". - Convert String to char:
try {
char c= str.charAt(0);
}
catch (IndexOutOfBoundsException e){
;
}
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?