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

Java如何判断int类型整数的首位数字是否为0?

How to check if an int in Java was declared with a leading zero?

Hey there! Let's tackle this question because there's a crucial gotcha in Java that you might not notice at first glance.

First, let's clarify what happens when you write int y = 0123;: in Java, any integer literal starting with 0 is treated as an octal (base-8) number, not decimal. So 0123 actually translates to the decimal value 83 (calculated as 1*8² + 2*8 + 3 = 64 + 16 + 3 = 83). Meanwhile, int n = 123; is a standard decimal integer with value 123.

The big problem here is: you can't tell from the stored int value alone whether it was declared with a leading zero. The variable y holds exactly the same value as int z = 83;—the leading zero from the declaration is lost once the number is converted to its integer value.

So how do we get the behavior you want (return true for y and false for n)? We need to preserve the original string representation of the number before it's parsed into an int. Here are two common scenarios and solutions:

Scenario 1: Handling user input

If you're dealing with numbers entered by a user (e.g., from the console), keep the input as a string first to check for leading zeros:

import java.util.Scanner;

public class LeadingZeroChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        // First validate it's a valid integer
        if (input.matches("0|[1-9]\\d*")) {
            // Check if length > 1 (to exclude single "0") and starts with '0'
            boolean hasLeadingZero = input.length() > 1 && input.charAt(0) == '0';
            System.out.println(hasLeadingZero);
        } else {
            System.out.println("Invalid integer input");
        }
        scanner.close();
    }
}
  • For input "0123", this returns true
  • For input "123", this returns false

Scenario 2: Tracking declared numbers in your code

If you need to track your own declared variables and their original leading-zero status, wrap the value and its declaration string in a custom class to preserve that context:

class TrackedInteger {
    private int value;
    private String originalDeclaration;

    public TrackedInteger(int value, String originalDeclaration) {
        this.value = value;
        this.originalDeclaration = originalDeclaration;
    }

    public boolean hasLeadingZeroInDeclaration() {
        // Check if the declaration starts with '0' and has digits following it
        return originalDeclaration.startsWith("0") 
            && originalDeclaration.length() > 1 
            && Character.isDigit(originalDeclaration.charAt(1));
    }

    public static void main(String[] args) {
        TrackedInteger y = new TrackedInteger(0123, "0123");
        TrackedInteger n = new TrackedInteger(123, "123");

        System.out.println(y.hasLeadingZeroInDeclaration()); // Outputs true
        System.out.println(n.hasLeadingZeroInDeclaration()); // Outputs false
    }
}

Key Takeaway

Always remember: int variables store numerical values, not their string representations. The leading zero from an octal literal is not part of the value—it's just a syntax marker for the compiler. To check for leading zeros, you must work with the string form of the number before it's converted to an int.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:43:48