Commit 56addfd
committed
feat(Package): add Test2 class using Optional for null-safe name retrieval
What
- Added Test2 class in package Package.
- Demonstrates use of java.util.Optional to avoid explicit null checks.
- main method:
- Calls getName(2) which returns an Optional<String>.
- Uses isPresent() guard before invoking get().
- Prints the contained value when present.
- getName(int id) returns Optional.of("Ram") as a non-null placeholder.
Why
- Shows idiomatic Java practice of returning Optional instead of null.
- Encourages safer API design by forcing callers to consider absence/presence explicitly.
- Example builds on Test class by moving from null-checks to Optional usage.
How
- Declared getName(int id) to return Optional<String>.
- Created a local String variable name = "Ram".
- Wrapped it using Optional.of(name).
- In main, assigned result to Optional<String> name.
- Used isPresent() to guard retrieval via get().
Logic
- Inputs: integer id (in example, 2).
- Outputs: "Ram" printed to stdout.
- Flow:
1. Call getName(2).
2. Inside getName: assign "Ram" to variable name.
3. Wrap value into Optional.of(name) and return.
4. In main: check if optional is present → true.
5. Print contained string using get().
- Edge cases handled:
- No risk of NullPointerException because Optional explicitly models presence.
- Current implementation always returns non-empty Optional.
- Complexity / performance: O(1) operations, negligible overhead for wrapping.
- Concurrency / thread-safety:
- No shared state, safe across threads.
- Optional is immutable.
- Error handling:
- No explicit exceptions thrown.
- Use of get() is safe here since guarded by isPresent().
Real-life applications
- Replacing APIs that previously returned null with Optional for better semantics.
- Teaching example of safe Optional usage.
- Encourages developers to handle empty values explicitly, avoiding hidden runtime bugs.
- Useful in repository/data layer methods returning optional entities.
Notes
- Current getName method always returns Optional.of("Ram"); future implementation may return Optional.empty() when no name found.
- In real-world code, prefer ifPresent() or orElse/orElseGet to avoid manual isPresent() + get() pairing.
- Example demonstrates Optional as return type, but avoid using Optional in fields or serialization targets.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 9072dd9 commit 56addfd
File tree
1 file changed
+17
-0
lines changed- Java 8 Crash Course/Lambda Expression/Optional/src/Package
1 file changed
+17
-0
lines changedLines changed: 17 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
0 commit comments