Java doesn't throw an error if you increase a number after its maximum value. If you wish to have this behaviour, you could use the Math.addExact(long x, long y) method from Java 8. This method will throw an ArithmeticException if you pass the Long.MAX_VALUE.

The reason why Java doesn't throw an exception and you receive negative numbers has to do with the way numbers are stored. For a long primitive the first byte is used for indicating the sign of the number (0 -> positive, 1 -> negative), while the rest are used for the numeric value. This means that Long.MAX_VALUE which is the biggest positive value will be stored as 01111...111 (0 followed by 63 bits of 1). Since you add a number to Long.MAX_VALUE you will start receiving negative integers since the sign byte changes to 1. This means you have an numeric overflow, but this error isn't thrown by Java.

Answer from Slimu on Stack Overflow
🌐
Coderanch
coderanch.com › t › 370696 › java › Test-negative-long
Test for negative long? (Java in General forum at Coderanch)
programming forums Java Mobile ... Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... Check to see if the long is less than zero. Example long myLong = -5L; System.out.println(myLong < 0); Prints "true" if negative....
Discussions

why does the value turn negative when i cast it from long to short?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
4
1
July 19, 2022
variables - Why adding positive values in Java or C# sometimes result in a negative value? - Software Engineering Stack Exchange
I was playing around with variables in Java. public class Hello { public static void main(String[] args) { byte byteV = 127; short shortV = Short.MAX_VALUE; int intV = Integer.MAX_VALUE; System.out.println("Short: " + shortV + ", Integer: " + intV); long longV = (10 * byteV) + shortV + intV; System.out.println(longV); } } The longV variable prints out a negative ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
does long long support negative values - general - CodeChef Discuss
problem : COINS Problem - CodeChef CODE 1 : CodeChef: Practical coding for everyone It gives correct answer CODE 2 : CodeChef: Practical coding for everyone It gives wrong answer Only difference being long long r[1… More on discuss.codechef.com
🌐 discuss.codechef.com
1
2
September 22, 2013
Negative int (or long) value deserialized incorrectly
If we test our request for getting ... the good negative value. But if we use Arango Java Driver, the resulting value is incorrect. For example, when storing -50 as long, the returned value is 206. Thanks for fixing it ... or helping to understand why it happens. ... You can’t perform ... More on github.com
🌐 github.com
8
September 27, 2017
🌐
Red-Green-Code
redgreencode.com › home › using integers and longs in java
Using Integers and Longs in Java - Red-Green-Code
October 7, 2015 - In this article, I’m going to focus on the signed versions of int, which uses 32 bits, and long, which uses 64 bits. Java also offers short (16 bits) and byte (8 bits) integer types, which may be useful for saving space in problems that involve large arrays of small numbers. Unsigned integers might be useful in edge cases, but puzzles usually define data to be well within the 32-bit range, or clearly outside of it. With 32 bits available for int, we can store about $2^{31}$ negative numbers and $2^{31}$ positive numbers.
🌐
Reddit
reddit.com › r/javahelp › why does the value turn negative when i cast it from long to short?
r/javahelp on Reddit: why does the value turn negative when i cast it from long to short?
July 19, 2022 -

why does it turn negative when i cast it from long too sort? can anyone explain how the binary system works here?

    System.out.println((short)32768.0);
Top answer
1 of 4
6
This is an example of integer overflow. The maximum value a signed short can have is 32767. https://en.m.wikipedia.org/wiki/Integer_overflow As for the binary: a short is 2 bytes or 16 bits. 32767 in 2s complement is 0111111111111111. The next binary number, 1000000000000000 is -32768 in 2s complement. https://en.m.wikipedia.org/wiki/Two's_complement Casting to a smaller integer type cuts off the most significant bits. 32768 = 00000000000000001000000000000000 Cutting off everything but the last 16 bits leaves us with 1000000000000000 which is -32768
2 of 4
3
The bits representing the long number is a bunch of zeros (to fill up the 64 bits) followed by: 1000000000000000 // 16 significant bits Now short is represented by only 16 bits, BUT, it's signed. This means that a bit is used to determine weather the number is positive or negative. From this follows that instead of representing numbers from 0 to 65535 it now represents the numbers from -32768 to 32767. Now imagine 16 bits where the most significant bit is representing the sign (+/-). When unsafely casting the big number to the short datatype it looks like this: 000....1000000000000000 // 64 bits (long) 1000000000000000 // casted to short which discards bit 17 to 64 (both included) The most significant bit in the short is a one, and this means that the number is negative. Most significant bit | V 1000000000000000 This means that now you are actually representing -32768, it might be more descriptive to say "negative zero" but that does not make sense so we have allocated the stand alone signed bit to expand the negative range from -32767 to -32768. Hope this helps, feel free to ask further questions 👍
🌐
Baeldung
baeldung.com › home › java › java numbers › check if a number is positive or negative in java
Check if a Number Is Positive or Negative in Java | Baeldung
January 8, 2024 - In Java, when we work with types like Integer, Long, Float, and Double, we often want to check if the numbers are positive or negative. This is a fundamental and common number operation. In this quick tutorial, we’ll discuss how to check whether a given number is positive or negative. Checking whether a number is positive or negative is a pretty straightforward problem. However, before we start looking at the implementations, let’s understand the definition of positive and negative.
🌐
LabEx
labex.io › tutorials › java-how-to-handle-negative-long-values-with-the-java-reverse-method-414059
How to handle negative long values with the Java reverse() method | LabEx
In this section, we'll explore ... guidance on how to effectively handle them. The reverse() method in Java treats negative long values the same way as positive long values....
🌐
Blogger
javarevisited.blogspot.com › 2013 › 01 › how-to-check-if-number-is-positive-or-negative-java-example.html
How to check if a Number is Positive or Negative in Java? Solution Example
Only Integer and Long can be checked to get the first character and comparing with "-". See How to convert Integer to String and Long to String in Java to convert these numbers into String.
Top answer
1 of 1
3

Numeric overflow

That's how Java and similar languages handle numeric overflow. In order to illustrate it, you can write a much simpler code:

public static void main(String[] args)
{
    int intV = Integer.MAX_VALUE;
    System.out.println(intV + 1);
}

which would produce -2147483648 as a result.

An answer on StackOverflow explains what happens under the hood, “binary-speaking”.

Note that doing this:

public static void main(String[] args)
{
    int intV = Integer.MAX_VALUE;
    long result = intV + 1;
    System.out.println(result);
}

since the intV + 1 part will be evaluated first, and only after that, the resulting value will be cast to a long. However, this would give a positive result, because the addition is now performed on a long value:

public static void main(String[] args)
{
    int intV = Integer.MAX_VALUE;
    long result = (long)intV + 1;
    System.out.println(result);
}

Specific handling of short

If you play with the first piece of code from my answer, you may end up writing code like this:

public static void main(String[] args)
{
    short shortV = Short.MAX_VALUE;
    System.out.println(shortV + 1);
}

You may be surprised to see that the result is 32768, which looks like nonsense since short can only store values from -32 768 to 32 767.

This is a particularity of Java (and similar languages such as C#) in a way the + operator works with short values. You can have a hint about what's going on by writing this piece of code:

public static void main(String[] args)
{
    short a = 5;
    short b = 4;
    short c = a + b;
    System.out.println(c);
}

This piece of code won't compile:

error: incompatible types: possible lossy conversion from int to short

What happens is that + operator first converts the short values to integers, and then produces the result. This is why in the piece of code above, you don't encounter a numeric overflow, since the addition is performed on an actual integer, and it's the value of an integer which is passed to println. On the other hand, this code:

public static void main(String[] args)
{
    short shortV = Short.MAX_VALUE;
    short result = (short)(shortV + 1);
    System.out.println(result);
}

will display -32768, because even if the addition itself resulted in 32768, the cast of 32768 to short produced a numeric overflow.

Find elsewhere
🌐
Oracle
docs.oracle.com › en › java › javase › 24 › docs › api › java.base › java › lang › Long.html
Long (Java SE 24 & JDK 24)
July 15, 2025 - The unsigned long value is the argument plus 264 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s. The value of the argument can be recovered from the returned string s ...
🌐
CodingTechRoom
codingtechroom.com › question › java-long-negative-overflow
How Can a Long Variable in Java Become Negative Without Exceeding Max Value? - CodingTechRoom
In Java, the `long` data type is a 64-bit signed integer capable of representing values from -2^63 to 2^63-1. When performing arithmetic operations, particularly addition, a long variable can overflow and wrap around to a negative value, even if it starts out within the maximum allowable range.
🌐
CodeChef Discuss
discuss.codechef.com › general
does long long support negative values - general - CodeChef Discuss
September 22, 2013 - problem : COINS Problem - CodeChef CODE 1 : CodeChef: Practical coding for everyone It gives correct answer CODE 2 : CodeChef: Practical coding for everyone It gives wrong answer Only difference being long long r[10000001]={-1}; long long func(int num) { if(num
🌐
GitHub
github.com › arangodb › arangodb-java-driver › issues › 151
Negative int (or long) value deserialized incorrectly · Issue #151 · arangodb/arangodb-java-driver
September 27, 2017 - We have java objects with a long (or int) filed. When storing negative values for these fields, if we check the database content with ArangoDB web interface, the collection contains a vertex with the good negative value.
Author: arangodb
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Long.html
Long (Java Platform SE 8 )
2 weeks ago - The unsigned long value is the argument plus 264 if the argument is negative; otherwise, it is equal to the argument. This value is converted to a string of ASCII digits in hexadecimal (base 16) with no extra leading 0s. The value of the argument can be recovered from the returned string s ...
🌐
Quora
quora.com › How-would-you-store-negative-numbers-as-integers-in-Java-without-losing-precision
How would you store negative numbers as integers in Java without losing precision? - Quora
Answer (1 of 2): You would store negative integers as integers. Whose values are less than zero. Integers do not lose precision by being negative. Why would storing negative numbers lose any more precision than positive numbers? Precision only matters for double. The precision of a double is th...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Long.html
Long (Java Platform SE 7 )
The following characters are used as octal digits: 01234567 These are the characters '\u0030' through '\u0037'. ... Returns a string representation of the long argument as an unsigned integer in base 2. The unsigned long value is the argument plus 264 if the argument is negative; otherwise, ...
🌐
Stack Overflow
stackoverflow.com › questions › 71485879 › getting-a-negative-number-for-a-long
java - Getting a negative number for a long - Stack Overflow
Numbers can be negative, what's the problem with this? ... The size of the data going in is 36 bytes and will always be 36. The result is a negative on Java because it goes beyond the bound of max value for long.