Reputation: 4325
int n ;
n= (int)( javax.swing.JOptionPane.showInputDialog(null,"enter a 3 digit no."));
Why does the above gives error[required int, found string] and the below one works fine ?
int n ;
n= Integer.parseInt( javax.swing.JOptionPane.showInputDialog(null,"enter a 3 digit no."));
Upvotes: 3
Views: 2851
Reputation: 36542
Integer.parseInt
doesn't use casting but rather a simple algorithm to interpret the digits in the string as a number. Casting is done by the JVM directly on the primitive value or the compiler on the object reference. It can turn 4.5
into 4
(type conversion as it changes the underlying value) and ArrayList
into List
(reference casting as it doesn't modify the instance), but it cannot parse or format numbers natively.
Upvotes: 9
Reputation: 56089
Java only lets you make valid casts, i.e. ones it knows how to make. Casting a string to an int is nonsensical; parsing it is not.
Upvotes: 1
Reputation: 200168
Type casting is not type conversion, don't confuse the terms. Casting means reinterpreting the same binary representation as a value of another type. In Java there are conversions, but only between primitive numeric values. String is a reference type, I guess you know that.
Upvotes: 8