Sub topic 3
Choosing a Value with the Conditional Operator
The conditional operator ? : chooses one of two values. It checks a condition, which is an expression that is either true or false.
In condition ? first : second, Java evaluates only the chosen value. If the condition is true, it chooses first; otherwise, it chooses second.
Save this program as Main.java, then compile and run it. It also demonstrates the operators in the sections below.
public class Main {
static boolean check() {
System.out.println("checked");
return true;
}
public static void main(String[] args) {
int score = 70;
String label = score >= 60 ? "pass" : "retry";
System.out.println(label); // pass
String first = new String("Java");
String second = new String("Java");
System.out.println(first == second); // false
System.out.println(first.equals(second)); // true
int flags = 0b1010;
System.out.println(flags & 0b0010); // 2
System.out.println(false & check()); // checked, then false
System.out.println(4 << 1); // 8
System.out.println(-4 >> 1); // -2
System.out.println(-4 >>> 1); // 2147483646
System.out.println((int) 3.9); // 3
Object value = "Java";
if (value instanceof String) {
String text = (String) value;
System.out.println(text.length()); // 4
}
}
}Reference Equality versus Value Equality
An object is a piece of data created by a program. A reference points to an object. For references, == checks whether both point to the same object.
The two strings above are separate objects, so == gives false. The equals method compares their text and gives true. A method is a named set of instructions.
Bitwise and Non-Short-Circuit Boolean Operators
A bit is a binary digit: 0 or 1. The prefix 0b writes a number in binary. Bitwise operators work on bits: & selects shared 1 bits, | combines them, ^ selects differing bits, and ~ flips bits.
With boolean values, &, |, and ^ evaluate both sides. That is why check() runs even though the left side is false.
Signed and Unsigned Shifts
Shift operators move bits. << shifts left. >> shifts right and keeps the sign bit. >>> shifts right and fills the left side with zeros. Thus, shifting a negative number with >>> can produce a positive result.
Casting and Testing Types
A cast asks Java to treat or convert a value as another type. (int) 3.9 drops the decimal part. instanceof tests whether a value refers to an object of a given type. The test above makes the cast to String safe.
Calls, Object Creation, and Expression Statements
A method call runs a method. For example, text.length() returns the text length. new String("Java") creates an object.
An expression statement is an expression used as a complete statement. Method calls, assignments, and object creation can be expression statements. A calculation such as 2 + 3; cannot stand alone.
Exercise
What does false ? "yes" : "no" produce?
Show answer
"no", because the condition is false.