1

In this string eclipse showing dead code warning on "Not Match"?

 String b = ("goodString")==("goodString") ? "Condition Macth": "Not Match";

Does it check string even before compiling ?

String a = ("goodString".equals("goodString")) ? "Condition Macth" : "Not Match";

If i change to .equals the warning close.

  • 1
    Do you mean "Eclipse IDE" (to show a static inspection warning) or the "(Eclipse) Java compiler" (i.e. does it affect how things get compiled)? โ€“ Thilo Jan 24 '19 at 06:36
  • For "real-life" String comparisons, you would use `equals`. I suppose your question can be extended to cover that as well. โ€“ Thilo Jan 24 '19 at 06:38

2 Answers2

2

Eclipse may analyse your code in order to detect dead code.

In this particular case, it shows that warning because those values always have the same identity because of string interning, thus the condition is always true. Eclipse detects that and emits a warning.

If you use equals, the comparison is no longer a constant expression (JLS ยง 15.28), and it's no longer guaranteed to return true. Hence the warning disappears.


By the way, you should always use equals to compare strings.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • Upvote for the edit1! Since equals is a method and not a constant expression, eclipse can no longer determine dead code. This makes things clear! :) โ€“ Mohamed Anees A Jan 24 '19 at 07:00
0
String b = ("goodString")==("goodString") ? "Condition Macth": "Not Match";

Here , Eclipse IDE is enough smart to find the dead code. If "If" condition is found as always true, then it warns "else" part as dead code because it will never be executed. In this snippet ternary condition is always true, so showing dead code warning.

Mohd Yasin
  • 427
  • 1
  • 5
  • 13