3

This is very weird.

A class I wrote has the following data member:

final static long MAX_FILE_SIZE_BYTES = 50000000000L;

at one point in my code the following block is run

System.out.println("MAXFILESIZEBYTES: " + MAX_FILE_SIZE_BYTES);

and the output is:

MAXFILESIZEBYTES: -1539607552

My question is, why is this long value overflowing? Java is supposed to be machine independent, and longs are supposed to hold 64 bits. What gives?

almel
  • 7,178
  • 13
  • 45
  • 58
  • Give details about your computer. And maybe your **java runner** is only 32bit, for example, running in Windows' 32bit compatible mode. – ch271828n Apr 16 '15 at 22:44
  • 8
    Please provide a minimal and _complete_ example that demonstrates the problem. – Jeffrey Bosboom Apr 16 '15 at 22:47
  • 3
    I can only get that output if I cast `MAX_FILE_SIZE_BYTES` to an `int` when printing. – rgettman Apr 16 '15 at 22:49
  • works for me: public class asdf { final static long MAX_FILE_SIZE_BYTES = 50000000000L; public static void main(String[] args) { System.out.println("MAXFILESIZEBYTES: " + MAX_FILE_SIZE_BYTES); } } – escitalopram Apr 16 '15 at 22:49
  • Cannot duplicate this with openjdk version "1.8.0_40" 64 bit on fedora 21. – Sinkingpoint Apr 16 '15 at 22:51
  • With the current 3 steps you have, the output is most definitely supposed to be 5E10. Try and look carefully around for code that might be mutating the value and if that hasn't worked do as Jeffery Bosboom says -posting an [SSCCE](http://sscce.org/) – Bennett Yeo Apr 16 '15 at 22:52
  • could be a bug in the the compiler you have. What version is it? my code compiles to `LDC "MAXFILESIZEBYTES: 50000000000"` – BevynQ Apr 16 '15 at 22:52
  • @rgettman I didn't get that output when I popped it into [Ideone (online compiler)](http://ideone.com/). Also a java int's cap is (−9,223,372,036,854,775,808 to +9,223,372,036,854,775,807) so overflow shouldn't be a problem right? – Bennett Yeo Apr 16 '15 at 23:00
  • 4
    @KiroYakuza [I did](http://ideone.com/7i8m6s). You've given `long`'s range; `int`'s range is -2,147,483,648 to +2,147,483,647. – rgettman Apr 16 '15 at 23:05
  • possible duplicate of [java number exceeds long.max\_value - how to detect?](http://stackoverflow.com/questions/12348067/java-number-exceeds-long-max-value-how-to-detect) – harshtuna Apr 16 '15 at 23:22
  • see [java lang spec](https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2) - `The integer operators do not indicate overflow or underflow in any way.` – harshtuna Apr 16 '15 at 23:23

1 Answers1

4

Cannot reproduce.

50000000000L is 0x0000000BA43B7400.

-1539607552 is FFFFFFFFA43B7400, which is what you would get if you cast the value to int.

Ergo somewhere you are casting it to int. Maybe you have a shadowed variable.

user207421
  • 305,947
  • 44
  • 307
  • 483