Mohammad
Mohammad

Reputation: 7418

Converting string types into integer types in Java

I know of this

Integer.parseInt(args[0]);

though in some other code I noticed this counts[(int) B.get(file,rank)]; where the (int) is supposedly converting the returned value from B.get into a Integer.

I can understand the validity of the Integer.parseInt statement, but where does the second one come from and is it proper Java code?

Upvotes: 0

Views: 1028

Answers (3)

maaartinus
maaartinus

Reputation: 46382

IMHO, this is a non-sense, casting to Integer together with autoboxing would be fine, but I know no single case when this compiles without warning and without error.

final Map<String, Integer> m1 = new HashMap<String, Integer>();
m1.put("a", 42); // autoboxing
final int n = (int) m1.get(42); // WARNING: Unnecessary cast from Integer to int


final Map<String, Long> m2 = new HashMap<String, Long>();
m2.put("a", 43L); // autoboxing
final int n2 = (int) (long) m2.get(42); // fine
final int n2a = (int) m2.get(42); // ERROR: Cannot cast from Long to int

final Map<String, Object> m3 = new HashMap<String, Object>();
m3.put("a", 43); // autoboxing
final int n3 = (Integer) m3.get(42); // fine
final int n3a = (int) m3.get(42); // ERROR: Cannot cast from Object to int

Maybe it was a cast to Integer?

Upvotes: 1

Michael Berry
Michael Berry

Reputation: 72254

Integer.parseInt() takes a string and converts that to a int.

Using (int) is just a cast, which won't work with a string. Casting works by telling the compiler that you know the object you've got is already of that particular type. The compiler trusts, you - if you get this wrong you'll face a ClassCastException (though the compiler will moan at you if it works out that the cast can never work if the objects aren't part of the same inheritance hierarchy.)

In the case of primitives casting can be used to demote primitives from one type to another, so casting a double to an int works by dropping the decimal component.

Upvotes: 1

Jacob Mattison
Jacob Mattison

Reputation: 51052

The second one is a cast; it doesn't turn one kind of object into another kind, but it allows you to change the form in which you are using the object.

Say I have an object of type Mammal but I happen to know that this particular instance is a Cat. I can do (Cat)myMammal and refer to the methods and properties that a Cat would have.

Needless to say this isn't a way to convert a string to an int. In the example you gave, you're taking an object of undetermined type (the output of get) and asserting that it's an int. This will only work if it really is an int.

If you want to convert a string to an int, you have to parse.

Upvotes: 3

Related Questions