I came across this syntax:
System.out.println(boolean_variable ? "print true": "print false");
The println(boolean) method of PrintStream Class in Java is used to print the specified boolean value on the stream and then break the line. This boolean value is taken as a parameter. Parameters: This method accepts a mandatory parameter booleanValue which is the boolean value to be written on the stream.
Answer: Boolean is a primitive data type that takes either “true” or “false” values. So anything that returns the value “true' or “false” can be considered as a boolean example. Checking some conditions such as “a==b” or “a<b” or “a>b” can be considered as boolean examples. Q #3) Is boolean a keyword in Java?
Boolean compare() method in Java with ExamplesThe compare() method of Boolean class is a built in method in Java which is used to compare two boolean values.
A boolean variable in Java can be created using the boolean keyword. Unlike C++, a numerical value cannot be assigned to a boolean variable in Java – only true or false can be used. The strings “true” or “false” are displayed on the console when a boolean variable is printed.
? :
is the conditional operator. (It's not just the :
part - the whole of the method argument is one usage of the conditional operator in your example.)
It's often called the ternary operator, but that's just an aspect of its nature - having three operands - rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It's called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.
The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false... and that ends up as the result of the operator.
So something like this:
int x = condition() ? result1() : result2();
is roughly equivalent to:
int x;
if (condition()) {
x = result1();
} else {
x = result2();
}
It's important that it doesn't evaluate the other operand. So for example, this is fine:
String text = getSomeStringReferenceWhichMightBeNull();
int usefulCharacters = text == null ? 0 : text.length();
It's the conditional operator, often called ternary operator because it has 3 operands: An example would be:
int foo = 10;
int bar = foo > 5 ? 1 : 2; // will be 1
int baz = foo > 15 ? 3 : 4; // will be 4
So, if the boolean
expression evaluates to true
, it will return the first value (before the colon), else the second value (after the colon).
You can read the specifics in the Java Language Specification, Chapter 15.25 Conditional Operator ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With