In Java, the ? symbol is used as part of the ternary operator, which is a shorthand for an if-else statement. The ternary operator has the following syntax:
condition ? expression1 : expression2;
How it works:
condition: The condition is evaluated. If it’s true, expression1 is executed; if it’s false, expression2 is executed.
expression1: The value returned if the condition is true.
expression2: The value returned if the condition is false.
Example:
int age = 18;
String result = (age >= 18) ? “Adult” : “Minor”;
System.out.println(result); // Outputs: “Adult”
In this example, the ternary operator checks if age is greater than or equal to 18 and assigns “Adult” if true, or “Minor” if false.