为何编译器认为表达式1 + m=6 + 2的结果是布尔类型?
1 + m = 6 + 2 as a boolean type? Great question—let's unpack this piece by piece, because there's a mix of precedence rules, valid Java syntax, and Eclipse's error messaging at play here.
First, let's clarify the core issues with the expression itself, then tackle why Eclipse mentions a boolean type:
1. The expression is syntactically invalid (regardless of m's state)
You're right that = has the lowest precedence in Java, so the compiler would logically try to evaluate the + operations first, leading to (1 + m) = (6 + 2). But here's the problem: you can only assign values to variables in Java, not to expressions that evaluate to a fixed value. 1 + m is an expression that computes a number—it's not a variable you can overwrite, so this assignment is never valid, even if m is initialized.
2. The two scenarios you mentioned
Let's break down what happens in each case:
- When
mis uninitialized:
The compiler throws an error first: "The local variable m may not have been initialized". It can't even get to checking the assignment validity because using an uninitialized local variable is a fundamental error.int m; 1 + m = 6 + 2; // Compile error - When
mis initialized:
Now the compiler catches the invalid assignment: "The left-hand side of an assignment must be a variable". This is the root syntax error here—you can't assign 8 to the value 2 (the result ofint m = 1; 1 + m = 6 + 2; // Compile error1+1).
3. Why does Eclipse say the result is boolean?
This hint is tied to the context where you're using the expression. Chances are you're putting it somewhere that expects a boolean value, like an if condition or assigning it to a boolean variable:
int m = 1; if (1 + m = 6 + 2) { // Eclipse flags this with a boolean-related message // ... }
Here's what's happening:
- The
ifstatement requires a boolean expression, so Eclipse is pointing out that the expression you provided doesn't match the expected boolean type. - Even if the assignment were valid (which it's not), the result of
a = bin Java is the value ofb(aninthere). Java doesn't allow implicit conversion frominttoboolean, so the compiler combines the invalid assignment error with the type mismatch for the expected boolean context.
In short: The expression is invalid because you can't assign to a computed value, and the "boolean type" message from Eclipse is a side effect of using the expression in a context that expects a boolean.
内容的提问来源于stack exchange,提问作者inqi777

