Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java calling method and using ternary operator and assign in the parameters?

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?.

like image 485
Oscar Gomez Avatar asked Dec 13 '22 11:12

Oscar Gomez


2 Answers

Parenthesis to the rescue!

doSomething(myString = ( ( myString != null ) ? myString.toLowerCase() : myString ), null)

To understand this, you need to know two things:

  • How the ternary operator works
  • The fact that the assignment operator returns the thing it is assigning
like image 62
tskuzzy Avatar answered May 16 '23 07:05

tskuzzy


Its just a more complicated version of:

public static doAnotherThing(String myString) 
{
  myString = myString != null ? myString.toLowerCase(): myString;
  return doSomething(myString, null) 
}

or even

public static doAnotherThing(String myString) 
{
  String s = myString;
  if (myString != null)
      s = myString.toLowerCase();
  return doSomething(s, null) 
}
like image 45
John Gardner Avatar answered May 16 '23 07:05

John Gardner