3
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."));

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You cannot cast an int to a boolean.
8

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.