I
I
Igor Petrov2012-05-05 15:52:12
Java
Igor Petrov, 2012-05-05 15:52:12

Dynamic type conversion and overflow

Hello!

I'll start with a puzzle that can be found literally in the first chapter of Java™ Puzzlers: Traps, Pitfalls, and Corner Cases by Joshua Bloch and Neal Gafter:

public class LongTest {
    public static void main(String ... args) {
      final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;
      final long MILLIS_PER_DAY   = 24 * 60 * 60 * 1000;
      System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
   }
}


What will be the result? (Answer below*)

Actually, in this thread I would like to ask the experts about overflow.
Let's say if we have an int and an overflow occurs at some stage. Why not do it in order to allocate new memory at this moment, but already of type long and move the value of the old variable there.
I suspect that this was done for performance purposes, but I'm not sure.

PS *Personally, I did not expect that the answer to the puzzle would be 5.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
L
leventov, 2012-05-05
@leventov

Let's say if we have an int and an overflow occurs at some stage. Why not do it in order to allocate new memory at this moment, but already of type long and move the value of the old variable there.

If you're talking about a class field, or even a local variable, then obviously you can't do that.
In the above example, the case is slightly different - the anonymous expression is evaluated in terms of the maximum operand, and not in the cell where the result will be written. Apparently, it cannot be done otherwise, because it is precisely this behavior that the JLS fixes. That is, it was thought out 1) in the mid-90s, 2) with an eye on C semantics.
Although the behavior is really harmful and illogical.

S
serso, 2012-05-06
@serso

Number overflow masking is a recognized mistake in the design of the Java language (we read the same Bloch).

G
galaxy, 2012-05-06
@galaxy

Why not do it in order to allocate new memory at this moment, but already of type long and move the value of the old variable there

Unlike Java, the developers of good languages ​​(PHP) did not stop at such a half-hearted solution and went further - they immediately convert to double, which is very logical and convenient for programmers, because you can, for example, calculate the age of the universe in nanoseconds.
A string that starts with a number can be expected to be converted to int, and a string that starts with a curly brace can be converted to object , oh, this is in PHP6 ... I
remember a joke: we would have your problems, Mary Ivanna

C
cypok, 2012-05-05
@cypok

javac is fucking numeric final fields and variables without any regrets, you bastard!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question