Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Implicit Casting in Numeric Literal Assignments

Joshua Smith
Ranch Hand
Posts: 193
I've been lurking on this forum for a short while now and am impressed with the depth of knowledge here and the quality of the questions being asked and the answers being given. After reading some of the posts here I went back and played with a few things with the compiler and came up with some strange results. I thought I'd post them here for everyone's benefit and maybe folks here could provide some insight on why they are that way. I've posted each of the questions separately so as not to confuse things and so the topic can be easily discerned from the Subject line. Here is the first one:

byte b = 1 compiles. float f = 1.0 does not. Based on things I've read in other posts in this forum I've been lead to believe that implicit casting takes place during numeric assignment if the right side of the equals sign is all numeric literals.

The assignment of an int literal to a byte (byte b = 1) becomes the assignment of a byte to a byte (byte b = (byte)1) by implicit cast.

Shouldn't the assignment of a double literal to a float (float f = 1.0) become the assignment of a float to a float (float f = (float)1.0) by implicit cast? It seems that it doesn't. Why is that?

Thanks,
Josh

Related post:
http://www.coderanch.com/t/250260/java-programmer-SCJP/certification/Implicit-cast

raghu babu
Ranch Hand
Posts: 60
implicit narrowing rules are applicable only to integer type not to floating point numerals. Hope this helps.

Ranch Hand
Posts: 69
Implicit narrowing primitive conversions are only allowed for int, short, char, and byte, and it's limited (I believe) to only assignment conversions on constant expressions. It's also allowed in the method return context only because that's considered to be an assignment by the compiler (this is a bit obscure).

Floats and doubles can't obey the same rules because of the complex (and somewhat inexact) way in which floating point numbers are represented in binary.

I'm not sure why longs were not included in the list of candidates for implicit narrowing, other than that ints are the default non-decimal literal and I have no idea why you'd deliberately make a narrowing primitive conversion on a constant expression that included a long.

JLS Spec
Article on implicit narrowing
[ August 24, 2005: Message edited by: Ryan Kade ]

Joshua Smith
Ranch Hand
Posts: 193
Good to know. I think I've probably run across some other behavior differences between integral and floating point numbers that might relate to this.

Thanks,
Josh