You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java整数加法编译报错:数值超出int类型范围问题咨询

Hey there! Let's break down why you're getting that error and how to fix it quickly.

The Root Cause

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.

Quick Fix: Switch to 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:

  1. Change the variable type from int to long
  2. Add an L suffix to the large number literal to tell the compiler it's a long (otherwise it still tries to treat it as an int)

Here's the corrected code:

public class Arithmetic {
    public static void main(String[] args) {
        long myNumber = 3 + 146367789778966L;
        System.out.println(myNumber);
    }
}
What If You Need Even Bigger Numbers?

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);
    }
}
Quick Cheat Sheet for Java Integer Ranges

Just to keep in mind for future reference:

  • byte: -128 to 127
  • short: -32768 to 32767
  • int: -2147483648 to 2147483647
  • long: -9223372036854775808 to 9223372036854775807

That should get your code running smoothly!

内容的提问来源于stack exchange,提问作者Thoth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:46:18