-4

If someone could explain how this code works I would greatly appreciate it as I cannot find a great example online elsewhere. It is the code used for defining strings in a toString method that was given with the example. These are the lines I do not understand, and under is the whole method.

getCity().length() > 0 ? getCity() : "N/A";
year != 0 ? "" + year : "N/A";
public String toString() {

    String displayString = getAuthor() + ", " + getTitle();
    String tempCity = getCity().length() > 0 ? getCity() : "N/A";
    String tempYear = year != 0 ? "" + year : "N/A";
    displayString += " (" + tempCity + ", " + tempYear + ")";
    displayString = displayString.length() < 73 ? displayString
                    : displayString.substring( 0, 69 ) + "...";

    return displayString;

}
  • 5
    Does this answer your question? [Benefits of using the conditional ?: (ternary) operator](https://stackoverflow.com/questions/3312786/benefits-of-using-the-conditional-ternary-operator) – Shivam Puri Nov 08 '20 at 20:34
  • 1
    Read about ternary operators – Shivam Puri Nov 08 '20 at 20:34
  • Hey there, Its ternary operator that works like if-else check out more here. https://www.programiz.com/java-programming/ternary-operator It simply check if the first condition is valid then execute the part after (?) and if its false execute the part after (:) In your case its checking it the getCity().length() > 0 if yes then whatever the output of getcity() else "NA" – RohitS Nov 08 '20 at 20:34
  • Useful search strategy: [java operator with question mark and colon site:http://stackoverflow.com](https://www.google.com/search?q=java+operator+with+question+mark+and+colon+site:http://stackoverflow.com) – DontKnowMuchBut Getting Better Nov 08 '20 at 20:48

2 Answers2

1

The first section is about if statement. first, it gets the length of the city name and it should be greater than zero, then if it's true getcity() calls if it's false "N/A" turns.

1

https://www.geeksforgeeks.org/java-ternary-operator-with-examples/

It string:

String tempCity = getCity().length() > 0 ? getCity() : "N/A";

equals it

String tempCity;
if(getCity().length() > 0) {
   tempCity = getCity();
}else {
   tempCity = "N/A";
}