Top answer
1 of 3
14

First of all, consider that the check is complex and probably relatively time consuming to do. It requires some static analysis, and there might be quite a bit of code between the two calls.

Second, the idiomatic usage of the two constructs are very different. I program full time in Scala, which uses Options much more frequently than Java does. I can't recall a single instance where I needed to use a .get() on an Option. You should almost always be returning the Optional from your function, or be using orElse() instead. These are much superior ways to handle missing values than throwing exceptions.

Because .get() should rarely be called in normal usage, it makes sense for an IDE to start a complex check when it sees a .get() to see if it was used properly. In contrast, iterator.next() is the proper and ubiquitous usage of an iterator.

In other words, it's not a matter of one being bad and the other not, it's a matter of one being a common case that's fundamental to its operation and is highly likely to throw an exception during developer testing, and the other being a rarely used case that may not be exercised enough to throw an exception during developer testing. Those are the sorts of cases you want IDEs to warn you about.

2 of 3
15

The Optional class is intended to be used when it is not known whether or not the item it contains is present. The warning exists to notify programmers that there is an additional possible code path that they may be able to handle gracefully. The idea is to avoid exceptions being thrown at all. The use case you present is not what it is designed for, and therefore the warning is irrelevant to you - if you actually want an exception to be thrown, go ahead and disable it (although only for this line, not globally - you should be making the decision as to whether or not to handle the not present case on an instance by instance basis, and the warning will remind you to do this.

Arguably, a similar warning should be generated for iterators. However, it has simply never been done, and adding one now would probably cause too many warnings in existing projects to be a good idea.

Also note that throwing your own exception can be more useful than just a default exception, as including a description of what element was expected to exist but didn't can be very helpful in debugging at a later point.

Discussions

Deprecating: java.util.Optional.get()?
I am generally in favor of letting the type system do as much work as possible - that is, if at all possible, anything that typechecks will actually not blow up. The problem is that we do have to bridge code that uses different interfaces, and was written at different times. My vote is we deprecate it and replace with getOrThrow(). That sounds sufficiently scary to me. More on reddit.com
🌐 r/java
44
68
April 28, 2016
GoTimeUtilTest : Remove call to `Optional.get()` without `isPresent()` check
Component JKube Kit Task description Description In GoTimeUtilTest, we're directly calling Optional.get() without checking whether there is any element present in the Optional, this might cause NoS... More on github.com
🌐 github.com
4
April 24, 2024
squid:S3655 (Optional value should only be accessed after calling isPresent()) being fired even though control will never reach the optional.get() call
We’re using SonarQube server Version 6.7.5 (build 38563). With default settings & the sonar-way quality profile. We have a lot of code like this: Optional optional = ... if (optional.isEmpty()) { throw new Exception("Error"); } var value = optional.get(); This triggers S3655 every time & ... More on community.sonarsource.com
🌐 community.sonarsource.com
3
0
May 14, 2019
Optional.get() is code smell
if (emailOpt.isPresent()) { sendEmail(emailOpt.get()); } emailOpt.ifPresent(email -> sendEmail(email)); if (email != null) { sendEmail(email); } trySend(email); email?.send(); More on reddit.com
🌐 r/programming
158
107
February 2, 2018
🌐
DZone
dzone.com › coding › java › java 8 optional—replace your get() calls
Java 8 Optional—Replace Your Get() Calls
July 5, 2016 - Calling get() without checking that value is actually present it’s a bug. So we should always write something like that in order to use get().\ Optional<String> myString = Optional.ofNullable(getNullableString()); if(myString.isPresent()){ doSomething(myString.get()); }
🌐
Reddit
reddit.com › r/java › deprecating: java.util.optional.get()?
r/java on Reddit: Deprecating: java.util.Optional.get()?
April 28, 2016 - But it's definitely not wrong when you're just using it as a null check like this: Optional<Integer> maybeGetInt() { .... } void doSomething() { Optional<Integer> maybeInt = maybeGetInt(); if (maybeInt.isPresent()) { doStuff(maybeInt.get()); } else { doSomethingElse(); } } I may have misinterpreted you but is that what you're saying your interviewee did? To me that is clearly superior to having maybeGetInt() return Integer, it being the caller's responsibility to handle a null without the method signature making it clear.
🌐
GitHub
github.com › eclipse-jkube › jkube › issues › 2970
GoTimeUtilTest : Remove call to `Optional.get()` without `isPresent()` check · Issue #2970 · eclipse-jkube/jkube
April 24, 2024 - Component JKube Kit Task description Description In GoTimeUtilTest, we're directly calling Optional.get() without checking whether there is any element present in the Optional, this might cause NoS...
Author   eclipse-jkube
🌐
SourceForge
sourceforge.net › home › browse › findbugs › feature requests
FindBugs / Feature Requests / #302 Add "isNull -> get"-rule for Java 1.8's new type Optional
June 27, 2014 - Since 1.8 Java has a type Optional which might or might not contain a not-null value. Best practice is to always call isPresent() before calling get() (similar to the annotation CheckForNull).
🌐
JetBrains
intellij-support.jetbrains.com › hc › en-us › community › posts › 360004508920--Optional-get-is-called-without-isPresent-check-losing-information-based-on-unrelated-asserts
'Optional.get() is called without isPresent()' check losing information based on unrelated asserts – IDEs Support (IntelliJ Platform) | JetBrains
The named inspection triggers on the `.get()` in the second `assert`, but not the first. @VisibleForTesting static Stream<FilterDifference> compareFilters( String hostname, String filtername, List<LineAction> currentActions, List<BDD> currentLineBdds, List<LineAction> referenceActions, List<BDD> referenceLineBdds) { checkArgument(!currentLineBdds.isEmpty()); checkArgument(!referenceLineBdds.isEmpty()); checkArgument(currentActions.size() == currentLineBdds.size() - 1); checkArgument(referenceActions.size() == referenceLineBdds.size() - 1); assert currentLineBdds.stream().reduce(BDD::or).get().isOne(); assert referenceLineBdds.stream().reduce(BDD::or).get().isOne(); // warning on .get()
Find elsewhere
🌐
Community Platform
wearecommunity.io › communities › java_americas › articles › 3846
A better way to use Optional.
In this article, we explore a smarter approach to harnessing the power of Java's Optional class. Discover how functional programming techniques can simplify your code, enhance readability, and make your applications more robust. Say goodbye to lengthy null checks and hello to a more elegant way of working with Optional.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - This method supports post-processing on optional values, without the need to explicitly check for a return status.
🌐
Sonar Community
community.sonarsource.com › rules and languages › report false-positive / false-negative...
squid:S3655 (Optional value should only be accessed after ...
May 14, 2019 - We’re using SonarQube server Version 6.7.5 (build 38563). With default settings & the sonar-way quality profile. We have a lot of code like this: Optional optional = ... if (optional.isEmpty()) { throw new Exception("Error"); } var value = optional.get(); This triggers S3655 every time & ...
🌐
Codemia
codemia.io › home › knowledge hub › optional.get without ispresent check
Optional.get without isPresent check | Codemia
July 31, 2025 - The Optional.get() method offers a way to retrieve the value stored in an Optional. However, directly using Optional.get() without checking if the Optional contains a value using isPresent() can lead to exceptions if the Optional is empty:
🌐
Writeoncereadmany
writeoncereadmany.github.io › 2016 › 12 › optional-get-considered-harmful
Dec 21, 2016 - Optional.get() considered harmful
public static void helloKitty(Optional<Cat> kitty) { ifPresentOrElse( kitty, cat -> System.out.println(cat.meow()), () -> LOGGER.error("I tawt I taw a puddy tat?")); } public static <T> void ifPresentOrElse(Optional<T> optional, Consumer<T> consumer, Runnable task) { optional.ifPresent(consumer); if(!optional.isPresent()) { task.run(); } } ... When the unsafe-ness of Optional.get() is the behaviour you want, there is a better alternative: explicitly using Optional.orElseThrow() The world would be a better place without Optional.get() on the API
🌐
Medium
medium.com › @amittoor › fixing-java-8-optional-f347231b0f4a
Fixing Java 8 Optional: ifPresent with else | by Amit Toor | Medium
October 11, 2020 - My other option was to use isPresent() method with if else block (isPresent is different method than ifPresent, isPresent returns a boolean, Just clarification), but it beats the whole purpose of optionals. So I decided to something about it and I ended up writing a wrapper on java optionals.
🌐
Tom Gregory
tomgregory.com › gradle › java-optional
Optional in Java: Everything You Need To Know | Tom Gregory
July 17, 2022 - @Test public void canUseIsPresentAntiPattern() { Guitarist knopfler = new Guitarist("Mark", "Knopfler", "Money For Nothing"); Optional<Guitarist> guitaristOptional = Optional.of(knopfler); if (guitaristOptional.isPresent()) { System.out.println(guitaristOptional.get().getSignatureSong()); } assertEquals("Money For Nothing", outputStreamCaptor.toString().trim()); } As you can see, we need to explicitly check that isPresent returns true before calling get, to avoid a potential NoSuchElementException.
🌐
Qiita
qiita.com › java8
Optionalの正しい使い方 #java8 - Qiita
December 18, 2017 - */ private Optional<String> optional; private static void test1(String str) { Optional optional = Optional.ofNullable(str); /** * Optional.get()' without 'isPresent()' check */ optional.get(); } private static void test1(Optional<String> optional ) { /** * Optional<String>' used as type for parameter 'optional' Reports any uses of java.util.Optional<T>, java.util.OptionalDouble, java.util.OptionalInt, java.util.OptionalLong or com.google.common.base.Optional as the type for a field or a parameter.
🌐
Javacodehouse
javacodehouse.com › blog › java-optional-use
Java Optional | How and When to use it
January 4, 2024 - Optional<String> optional = // ... // Avoid using get() without checking isPresent() String value = optional.orElse("Default");
🌐
DZone
dzone.com › coding › languages › 26 reasons why using optional correctly is not optional
26 Reasons Why Using Optional Correctly Is Not Optional
November 28, 2018 - Using theOptional.orElseThrow()method represents another elegant alternative to theisPresent()-get()pair. Sometimes, when anOptionalvalue is not present, all you want to do is to throw ajava.util.NoSuchElementExceptionexception. Starting with Java 10, this can be done via theorElseThrow()method without arguments. For Java 8 and 9, please consider item 6. ... // AVOID public String findUserStatus(long id) { Optional<String> status = ... ; // prone to return an empty Optional if (status.isPresent()) { return status.get(); } else { throw new NoSuchElementException(); } }