Java如何判断int类型整数的首位数字是否为0?
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 returnstrue - For input
"123", this returnsfalse
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

