I was reviewing some code and I came across this:
public static doSomething(String myString, String myString2) {
//Stuff
}
public static doAnotherThing(String myString) {
return doSomething(myString = myString != null ? myString.toLowerCase(): myString, null)
}
How is this working exactly?, I know the .toLowerCase resulting string is assigned to myString (yes I know bad practice since you are not supposed to reassign method parameters in fact they should be final), but I am not quite sure how does the method always receives the 2 parameters it needs.
I know how it works when myString is null or at least I think I do, since the ternary has myString, null, but I am not quite sure why it would go there when myString is not null?.
This piece of code reassigns myString to be either myString.toLowerCase(), or it doesn't reassign it. But the act of using the assignment operator returns the value that was assigned, thus you are essentially calling this:
You should also note that Strings are immutable, and that changing the value of myString in doAnotherThing(String) will not affect the String that was passed into the method.
Parenthesis to the rescue!
To understand this, you need to know two things:
The code is confusing, but I am not sure what the problem is. The result of an assignment is the value assigned.
This
is the same as
Its just a more complicated version of:
or even
Assign into variable from ternary operator like so:
More examples: http://alvinalexander.com/java/edu/pj/pj010018
doSomething
receives two parameters, both of which are strings. IndoAnotherThing
:doSomething
is:null
ifmyString
isnull
,myString.toLowerCase()
otherwise.doSomething
is alwaysnull
.It might be clearer rewritten like this: