What does "?" mean in Java?
This question explains the usage of the ? symbol in Java, especially in generics and ternary operations, and clarifies how it contributes to flexibility and decision-making in code.
The ? symbol in Java can be a little confusing at first because it’s used in two very different contexts. Let’s break it down so it’s easy to understand.
1. Ternary (Conditional) Operator
This is probably the first place many developers encounter ? in Java. It acts like a shortcut for an if-else statement.
int a = 10;
int b = 20;
int max = (a > b) ? a : b; // max will be 20
- Here, ? works with : to form the ternary operator.
- It means: If a > b is true, return a; otherwise, return b.
- It's a concise way to write simple conditional expressions.
2. Wildcards in Generics
In Java Generics, ? is used as a wildcard, representing an unknown type.
List items = new ArrayList();
- This means the list can hold any type, but you can’t add new elements (other than null).
- It's helpful when you're reading data, but don’t need to modify the collection.
You can also use bounded wildcards like:
List numbers; // Any subclass of Number
List integers; // Integer or any superclass
Summary:
- Use ? with : in ternary operations for short conditionals.
- Use ? in generics to allow flexibility with types.
So, while the ? looks small, it plays a powerful role in making Java both expressive and type-safe!