Java命令行计算器if-else分支失效问题求助
Hey, I’ve seen this exact issue hundreds of times—you’re hitting a classic Java string comparison gotcha! Let’s break down what’s going wrong and how to fix it.
The Root Problem: Using == for String Content Comparison
In Java, the == operator checks if two object references point to the same memory location, not if their content is identical. When you get the command line argument z = args[2], that’s a new String object stored in the heap. The literal "add" lives in Java’s string constant pool, which is a separate area of memory. Even though their content is the same, their memory addresses are different—so z == "add" returns false, and your branch never triggers.
The Fix: Use equals() (or equalsIgnoreCase())
To compare the actual content of two strings, you need to use the equals() method built into the String class. If you want to avoid potential NullPointerException (in case z is ever null for some reason), flip the order to call equals() on the literal string instead:
Here’s how to adjust your code:
Original (broken) code snippet:
public class Calculator { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); String z = args[2]; System.out.println(z); // Prints "add" if (z == "add") { // This fails! System.out.println(a + b); } // Other branches... } }
Fixed code:
public class Calculator { public static void main(String[] args) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); String z = args[2]; System.out.println(z); // Prints "add" if ("add".equals(z)) { // Correct way to compare content System.out.println(a + b); } // Other branches... } }
If you need to ignore case (e.g., accept "Add" or "ADD" as valid), use equalsIgnoreCase() instead:
if ("add".equalsIgnoreCase(z)) { // Logic here }
Quick Side Note: Why Literal-to-Literal == Sometimes Works
You might have seen code like String s = "add"; if (s == "add") work before. That’s because Java reuses string literals from the constant pool—so both references point to the same object. But this doesn’t apply to strings created from command line arguments, new String(), or dynamic input, which are always new objects in the heap.
内容的提问来源于stack exchange,提问作者Saubhagya Srivastava

