Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Casting a String to an Integer type

Status
Not open for further replies.

slimmer

Programmer
Oct 21, 2002
11
US
Is it possible to cast a String to an Integer? I initially defined a variable as an int but received a CastClassException error when trying to sort the object.

If I define the element of the class as String, I do not receive the error however the values are not sorted as I expect (i.e. 0,1,12,13,14,3,4,5....)

I retrieve the value from the resultset as a string but need to change it to an Integer when adding the element to the class, also causing me to change the class definition to Integer instead of String.

I was using the getInt to retrieve the value from the recordSet but changed it to the getString. I did not see a method called getInteger.

Therefore, is my only option to make this work casting from String to Integer and can that be done?
 
Some examples.
Code:
    String s = "3";
    Integer i = new Integer(s);
    Integer j = Integer.valueOf(s);
    int k = Integer.parseInt(s);
    System.out.println(i.toString());
    System.out.println(j.toString());
    System.out.println(""+k);
Cheers, Neil
 
Just a qucik note on casting...
you cannot cast a String to an Integer, since you can only cast objects up or down the inheritance ladder. String and Integer are on the same level in the object hierarchy but on different branches, therefor casting is impossible. The example above uses a method to give you the result you want.
 
If I understand you correctly you would like to cast a String to an int. This could be done by using the static method pasreInt() int the class Integer

this could look something like this.

String i = "1";
int value = Integer.parseInt(i);


/Ztopovich
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top