Converting String into Primitive Types in java...Possible?

1.9k views Asked by At

I want to know that is it possible to convert String into char, int,float,double and other primitive types If yes then How.. If no then why..we can't do it. In primitive type we can convert any primitive into any other using Type Casting..so Is there Something to do so with the Strings. As we know that we can convert any primitive type into String ,so is it possible to convert String into Primitive types..

3

There are 3 answers

0
Shubhamhackz On BEST ANSWER

Finally found some really easy and working way..to convert String into Primitive Types... We Can use wrapper class for conversion But we have pay extra attention converting String into Primitive Types because we can only convert String into the requires primitive type if primitive type actually supports the data....i.e we can't convert a String into int if it's no(0 to 9), any other data will throw runtime exception...Same will be applied to all other Primitive Types

    //String to primitive types
int iVal = Integer.parseInt(str);
long lVal = Long.parseLong(str);
float fVal = Float.parseFloat(str);
double dVal = Double.parseDouble(str);
0
Marco Ingrosso On

Just use:

String str = "myString"; char[] charArray = str.toCharArray();

3
Gaurav Sahu On

Of course it is possible in java. As you know String is a class in java. this String class defines a method toCharArray() which is used to convert a String object to character array. Its return type is array of characters.

String str = "java";
char arr[];
arr = str.toCharArray();