Skip to content

Instantly share code, notes, and snippets.

@conorgriffin
Last active August 29, 2015 13:56
Show Gist options
  • Save conorgriffin/4d66fbe0f7a4f7e4b021 to your computer and use it in GitHub Desktop.
Save conorgriffin/4d66fbe0f7a4f7e4b021 to your computer and use it in GitHub Desktop.
Java Ternary Operator
// Example #1a
public class Person {
private int age;
public Person(int age) {
this.age = age;
}
public void isAdultOrChild() {
System.out.println(this.age >= 18 ? "Adult" : "Child");
}
public static void main(String[] args) {
Person child = new Person(7);
child.isAdultOrChild();
Person adult = new Person(42);
adult.isAdultOrChild();
}
}
// Example #1b
public void isAdultOrChild() {
if(this.age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Child");
}
}
// Example #2
int x = -10;
int absoluteValue = (x < 0) ? -x : x;
// Example #3
public String apples(int x) {
String statement = "There " + (x == 1 ? "is" : "are ") + String.valueOf(x) + " apple" + (x == 1 ? "" : "s") + " on the table";
}
// Output will be "There is 1 apple on the table"
System.out.println(apples(1));
// Output will be "There are 3 apples on the table"
System.out.println(apples(3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment