Last active
August 29, 2015 13:56
-
-
Save conorgriffin/4d66fbe0f7a4f7e4b021 to your computer and use it in GitHub Desktop.
Java Ternary Operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example #1b | |
public void isAdultOrChild() { | |
if(this.age >= 18) { | |
System.out.println("Adult"); | |
} else { | |
System.out.println("Child"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example #2 | |
int x = -10; | |
int absoluteValue = (x < 0) ? -x : x; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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