Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!npeer01.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!border3.nntp.dca.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!postnews.google.com!glegroupsg2000goo.googlegroups.com!not-for-mail From: Lew Newsgroups: comp.lang.java.programmer Subject: Re: floating point Date: Tue, 24 Jul 2012 13:21:33 -0700 (PDT) Organization: http://groups.google.com Lines: 61 Message-ID: References: NNTP-Posting-Host: 69.28.149.29 Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable X-Trace: posting.google.com 1343161294 4884 127.0.0.1 (24 Jul 2012 20:21:34 GMT) X-Complaints-To: groups-abuse@google.com NNTP-Posting-Date: Tue, 24 Jul 2012 20:21:34 +0000 (UTC) In-Reply-To: Complaints-To: groups-abuse@google.com Injection-Info: glegroupsg2000goo.googlegroups.com; posting-host=69.28.149.29; posting-account=CP-lKQoAAAAGtB5diOuGlDQk0jIwmH0T User-Agent: G2/1.0 X-Received-Bytes: 3313 Xref: csiph.com comp.lang.java.programmer:16311 markspace wrote: > bob smith wrote: >> I can never remember this. >> >> Let's say you have an integer and a float in an operation. Is the resul= t always a float? >=20 >=20 > You can just try this to see what you get, or read the JLS. From=20 Excellent advice. "Just trying it" could obscure some of the intermediate promotions. > memory, I'm 90% sure that ints will be promoted to floats. I'm not sure= =20 > how order of operations affects this. In the expression (1+1)/2.0f,=20 > does the addition use floats or ints? I'm not sure, but I think ints. From the JLS: "The left-hand operand of a binary operator appears to be fully evaluated= =20 before any part of the right-hand operand is evaluated." "The Java programming language respects the order of evaluation indicated= =20 explicitly by parentheses and implicitly by operator precedence." So, yes, the parenthesized addition is done as an 'int' addition. "5.6. Numeric Promotions "Numeric promotion is applied to the operands of an arithmetic operator.=20 Numeric promotion contexts allow the use of: " an identity conversion (=A75.1.1) " a widening primitive conversion (=A75.1.2) " an unboxing conversion (=A75.1.8) "Numeric promotions are used to convert the operands of a numeric=20 operator to a common type so that an operation can be performed.=20 The two kinds of numeric promotion are unary numeric promotion=20 (=A75.6.1) and binary numeric promotion (=A75.6.2)." So, by those sections you can see that the division must be evaluated=20 as 'float'. For those who decry the use of the JLS to learn this, just note that the=20 relevant sections are not especially obscure and they answer the=20 question completely and authoritatively. But feel free to struggle with=20 alternatives if you really want to work harder. --=20 Lew