0

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
  • 1
    String#toCharArray() Commented Sep 6, 2017 at 8:02
  • 4
    Possible duplicate of String to char array Java Commented Sep 6, 2017 at 8:04
  • Can we convert String into any other Primitive Types..like int or float.. Commented Sep 6, 2017 at 8:12

3 Answers 3

1

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();
Sign up to request clarification or add additional context in comments.

3 Comments

Is there any other way to do while converting to other Primitive Types?
for converting string to other primitive type its depends on your string value like String s="1" we can convert into int but String s="Hello" to int type we cannot typecast expetion will be there
@khushvinder Now I UnderStand
1

Just use:

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.