How to set text field to a defined value if the object is null from the getter method

Viewed 116

I have an object (eg. Person) in which it has a variable, eg. Friend which is also a Person object and it is set to null. In my GUI, there is this Friend field, in which it is supposed to display the name of the Friend.

As mentioned above, the friend variable can be a null and so, is there a one-liner in which I can used such that the text field can be set to a value "NA" if the object is null?

Currently I am getting nowhere other than the following line:

frenTextField.setText(personObject.getFrenObj().toString());
2 Answers

You can use this one-liner which uses ternary operator for conditional check for null object

frenTextField.setText(personObject.getFrenObj() == null ? "NA" : personObject.getFrenObj().toString());
Related