Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

casting in java

  Asked By: Madeleine    Date: Jul 22    Category: Java    Views: 679
  

one question, how can i cast a String variable to long in java.

Share: 

 

3 Answers Found

 
Answer #1    Answered By: Cesara Fernandez     Answered On: Jul 22

Although you cannot just cast  a String to a long, you
can parse out the value of a String that contains a
number and convert that to a long. You can use the
Long wrapper class and your code would look somewhat
like this:

try
{
String myString = "1234";
long myLong = Long.parseLong(myString);
}
catch (NumberFormatException nfe)
{
// handle the exception however appropriate...
// e.g.
nfe.printStackTrace();
}

 
Answer #2    Answered By: Daimon Jones     Answered On: Jul 22

Directly u can't cast  a String variable  into a Long.
Becoz String is an immediate child of Object class, so u can't directly cast
String into any other types except an Object class.
(Def. u know Object is the parent of all classes, so virtually u can't cast
a String variable into other types)
IF I AM WRONG PLZ LET ME KNOW...

But there are very simple,static methods like
new Long(String)
Long.parseLong(String)

which will return long  values.
u can use these to convert a String value to Long (Wrapper class) /
long(primitive).

 
Answer #3    Answered By: Aabirah Khan     Answered On: Jul 22

i would like to make an imp correction my mail that u can't DIRECTLY cast  a
String to any other type.
But u have functions provided in Wrapper classes to convert a String into
primitive data types;

Integer.parseInt(String);
Double.parseDouble(String);
Long.parseLong(String);
Float.parseFloat(String);

Boolean.valueOf(String); //True / False
Byte.valueOf(String);
Short.valueOf(String);

& all of Wrapper classes having their constructors with String type :)
new Integer(String);
new Double(String);
new Long(String);
new Float(String);
new Boolean(String);
new Byte(String);
new Short(String);

 
Didn't find what you were looking for? Find more on casting in java Or get search suggestion and latest updates.




Tagged: