user1779158
user1779158

Reputation: 13

Regarding casting of the outcome

I have a method which return type is string below is the method

public String getHwIdentifier();

Now I am using this method ..

String s = till.getHwIdentifier();//return type of this method is string

I want to cast it in integer that is something like this

Int i = till.getHwIdentifier();

Please advise how take integer means how to cast it..

Upvotes: 0

Views: 47

Answers (5)

user1784754
user1784754

Reputation: 11

String s = till.getHwIdentifier();
int i = Integer.parseInt(s);

Make sure that your string is in the form of an integer. If your string contains xyz then you will get a java.lang.NumberFormatException.

Upvotes: 0

J.A.I.L.
J.A.I.L.

Reputation: 10794

There is no Java type/class named Int. There's int type and it's encapsulating Integer class.

You can parse an integer in a String to the int value with Integer.parseInt("1234");, or get the Integer value with Integer.valueOf("1234");. But notice if the String doesn't represent an integer you'll get a NumberFormatException.

    String s = till.getHwIdentifier();//return type of this method is string;
    try
    {
      Integer a = Integer.valueOf(s);
      int b = Integer.parseInt(s);
    }
    catch (NumberFormatException e)
    {
      //...
    }

Note: You could use Integer a = Integer.decode(s);, but Integer c = Integer.valueOf(s); is preferred as it won't create new objects if possible.

Upvotes: 0

Kenrick Chien
Kenrick Chien

Reputation: 1046

Pass the instance of the String to Integer.valueOf(String s). So in your case:

Integer i = Integer.valueOf(till.getHwIdentifier);

See http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28java.lang.String%29 for more details.

Upvotes: 0

Abubakkar
Abubakkar

Reputation: 15654

Use parseInt(String s) method of Integer class which takes String and converts it to intif it is a number or throws NumberFormatException like this :

int i = Integer.parseInt(till.getHwIdentifier());

Upvotes: 1

PermGenError
PermGenError

Reputation: 46418

try parseInt from Integer class.

Integer.parseInt(till.getHwIdentifier());

but mind you, it'd throw NumberFormatException if the string is not a valid integer representation

Upvotes: 1

Related Questions