So far our operator arsenal have been mostly related to arithmetic or booleans. However, there is still a huge library of operators we have yet to learn, and I'm not even sure we'll get to them.
The third bonus question on our midterm, something our professor said we hadn't seen before, asked to explain what the ?: operator was. I'm guessing most of my classmates' responses were identical to mine: "I have no clue," but I'll try to break it down as best I can here.
The ?: operator, or the ternary operator, gives options. For example:
System.out.print("I have " + x + " apple" + (x==1 ? "" : "s");
Essentially, it analyzes a boolean (x == 1) and if it's true (?) it prints nothing after "apple". However, if the boolean is false, the ":" acts as an "else." If you have any amount other than 1 of apples, the correct sentence would be "I have x apples," whether x is less than or greater than 1. There are definitely other ways to do this with if-else statements, but this operator can help us shorten our code.
Image source:
http://stackoverflow.com/questions/19827668/does-java-have-identical-comparison-operator-example

No comments:
Post a Comment