Java整数加法编译报错:数值超出int类型范围问题咨询
Hey there! Let's break down why you're getting that error and how to fix it quickly.
Java's int data type has a strict size limit—it's a 32-bit signed integer, which means it can only hold values between -2147483648 and 2147483647.
Your number 146367789778966 is way larger than that upper bound—so big that the compiler can't even represent it as an int literal, hence the error you're seeing.
long For numbers this size, you should use Java's long type instead. It's a 64-bit integer that can handle values up to 9223372036854775807—plenty of room for your number.
Just two small changes to your code:
- Change the variable type from
inttolong - Add an
Lsuffix to the large number literal to tell the compiler it's along(otherwise it still tries to treat it as anint)
Here's the corrected code:
public class Arithmetic { public static void main(String[] args) { long myNumber = 3 + 146367789778966L; System.out.println(myNumber); } }
If you ever work with numbers that exceed the long limit, use BigInteger from the java.math package—it supports arbitrarily large integers. For your current case, this is overkill, but here's an example just in case:
import java.math.BigInteger; public class Arithmetic { public static void main(String[] args) { BigInteger myNumber = new BigInteger("146367789778966").add(BigInteger.valueOf(3)); System.out.println(myNumber); } }
Just to keep in mind for future reference:
byte: -128 to 127short: -32768 to 32767int: -2147483648 to 2147483647long: -9223372036854775808 to 9223372036854775807
That should get your code running smoothly!
内容的提问来源于stack exchange,提问作者Thoth

