File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Automatic Conversion / Cast Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Automatic Conversion / Cast" Watch "Automatic Conversion / Cast" New topic

Automatic Conversion / Cast

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
The automatic cast from float to int takes only place for first parameter.
Why not for the second, too?
I get this error:Why?
Why don't I get the error before?
[ edited to make code and error message more readable -ds ]
[ January 15, 2003: Message edited by: Dirk Schreckmann ]
John Lee
Ranch Hand

Joined: Aug 05, 2001
Posts: 2545
Originally posted by Thomas Markl:

Why don't I get the error before?

If I understand your question correctly, you are asking why:
float x = 1;
is ok.
int y = 1.0F
is not.
The reason is you can upcast implicitly. But when you want to downcast, your have to be explicitly.
int y= (int)1.0F
will work.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061

The above line doesn't do any automatic conversion. The variable y is declared as a float and the F indicates that the literal is a float, also.

This comparison DOES have an automatic conversion. The variable x is converted to a float so that operation can occur. When an the orpands for an operator have different types, the larger (more bits) type is usually used.

Here you are trying to assign a float literal to an int variable. Since int uses less bits than float, the compiler will complain. There is no automatic conversion from int to float, only from float to int.

If you can fix the above problem, this line will once again convert the int variable to a float.


Java API Documentation
The Java Tutorial
Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
I think, now I got it:
Comparison of primitive numbers with „==“ and
Objects like Integer or String with „==“ and „equals“.

C:\Java\EigeneJavaProgramme>java Test104
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Is this a new question? If so, what are you asking?
[ January 16, 2003: Message edited by: Layne Lund ]
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Note that the == operator doesn't compare obects. It compares object references. The expression ref1 == ref2 only returns true if ref1 and ref2 both refer to the exact same object.
Depending on how it's actually implemented, the equals method likely determines equality by considering the states of the objects in question.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Robbie shi

Joined: Jan 05, 2003
Posts: 28
float x=1; it is ok
int x=1.0f; cant happen
----------------------------- IDE tool : JawaBeginer
2.Java Jar tool : JavaJar
I agree. Here's the link:
subject: Automatic Conversion / Cast
It's not a secret anymore!