Reputation: 567
I have found a strange behavior of assertions in Java (Eclipse). Easy example: If i execute this...
public static void main (String[] args) {
assert(getA() == "a") : "Invalid";
System.out.println("Assertion successful!");
}
private static String getA()
{
return "a";
}
... it will show me "Assertion successful!" as it should. However if i try this...
public static void main (String[] args) {
assert(getA() + "b" == "ab") : "Invalid";
System.out.println("Assertion successful!");
}
private static String getA()
{
return "a";
}
... I get an AssertionError. How come this Assertion doesn't return true?
Note:
Upvotes: 0
Views: 139
Reputation: 45060
You need to give
"a".equals(getA());
Second case
"ab".equals("b".concat(getA()));
Reason:- ==
is for comparing object references, whereas equals()
is used for the string value comparison, which is what you needed. Plus, the first scenario had the same string literal "a", hence, it returned true
. But in the second case, a new instance of String was created for getA()+b
, which is different from the literal "ab".
Upvotes: 6
Reputation: 12398
"a"
is a literal on compile time, then "a"=="a"
evaluates as true
getA()+"b"
creates a new instance of String, which is different from the compile time literal "ab"
Upvotes: 5