Java Topics
HubJava Collections FrameworkCollections Practice ProgramsComparable vs ComparatorGenericsIteratorArrayListLinkedListStackVectorHashMapHashtableLinkedHashMapTreeMapArrayDequeDeque Double-Ended QueuePriorityQueueHashSetLinkedHashSetTreeSetAdapter PatternBuilder PatternFactory PatternMVC PatternObserver PatternSingleton PatternDynamic ProgrammingGraphHashingHeapLinked List DSAQueue DSARecursionSearching AlgorithmsSorting AlgorithmsStack DSATime ComplexityTreesException Handling Best PracticesCustom ExceptionException Hierarchyfinally BlockException Handlingthrow aur throwstry-catchBuffered StreamsByte StreamsCharacter StreamsDeserializationFile ClassJava NIO New I/OSerializationArrays in JavaArray OperationsArray Practice ProgramsArray Interview QuestionsJagged ArrayMulti-Dimensional ArraysOne Dimensional Arraybreak aur continuedo-while Loopfor Loopif-else StatementsNested Loopsswitch-case Statementwhile LoopJava Compilation ProcessJava ki FeaturesPehla Java ProgramHistory of JavaJava EditionsJava Program StructureJDK, JRE aur JVMJava Kya Hai?Immutable StringsString Class in JavaString Interview QuestionsString MethodsString Practice ProgramsStringBufferStringBuilderComments in JavaData Types in JavaIdentifiers in JavaInput & Output in JavaJava KeywordsOperators in JavaType Casting in JavaVariables in JavaJava Coding Interview QuestionsCollections Interview QuestionsCore Java Interview QuestionsJDBC Interview QuestionsMultithreading Interview QuestionsOOPs Interview QuestionsSpring Framework Interview QuestionsJava 8 Date/Time APIDefault aur Static Methods in InterfaceFunctional InterfaceLambda ExpressionMethod ReferenceOptional ClassStream APIBatch ProcessingCallableStatementJDBC ArchitectureJDBC — Java Database ConnectivityJDBC Practice ProjectsMySQL ConnectionPreparedStatementResultSetStatement InterfaceTransaction ManagementCreating ThreadsDaemon ThreadExecutor FrameworkInter-Thread CommunicationMultithreading Practice ProgramsRunnable InterfaceSynchronizationThread ClassMultithreading IntroductionThread Life CycleThread PriorityJava Cheat SheetImportant Formulas & Key ConceptsImportant Java ProgramsJava Quick RevisionAbstract ClassAbstractionAnonymous ClassClass and ObjectConstructorEncapsulationInheritanceInner ClassInterfaceMethod OverloadingMethod OverridingObject ClassObject CloningObject-Oriented Programming OOPPolymorphismstatic Keywordsuper Keywordthis KeywordWrapper ClassesArray Practice ProgramsBasic Java Practice ProgramsCollection Practice ProgramsJDBC Practice ProgramsMultithreading Practice ProgramsOOPs Practice ProgramsPlacement Coding QuestionsString Practice ProgramsBanking SystemChat ApplicationE-Commerce Backend — Spring Boot REST APIEmployee Management SystemLibrary Management SystemSpring Boot Fullstack ProjectStudent Management SystemCookies in ServletExpression Language ELGenericServletHttpServletJavaServer Pages JSPJSP TagsMVC ArchitectureHttpServletRequest & HttpServletResponseServlet IntroductionServlet Life CycleSession TrackingDependency InjectionSpring BeansSpring CoreSpring FrameworkAPI GatewaySpring Cloud Config ServerDocker DeploymentEureka Server — Service DiscoverySpring Boot CRUD ApplicationException Handling in Spring BootJWT AuthenticationREST API in Spring BootSpring SecuritySpring BootSpring Data JPAValidation in Spring Boot
Optional Class
Last Updated : 26 May, 2026
title: Optional Class in Java 8
Java 8 Features35 words4 headingsExamples included
title: Optional Class in Java 8 description: NullPointerException se bachao - Optional class
null return karne ki jagah Optional use karo. NullPointerException se bachata hai.
Create karna
java exampleWoHoTech
Optional<String> opt1 = Optional.empty(); // Empty optional
Optional<String> opt2 = Optional.of("Hello"); // Non-null value (null → exception)
Optional<String> opt3 = Optional.ofNullable(null); // null ya value dono OKMethods
java exampleWoHoTech
Optional<String> opt = Optional.of("Java 8");
opt.isPresent() // true
opt.isEmpty() // false (Java 11+)
opt.get() // "Java 8" (exception if empty)
opt.orElse("Default") // "Java 8" (Default if empty)
opt.orElseGet(() -> "Computed") // Lazy default
opt.orElseThrow() // Throw NoSuchElementException if empty
opt.orElseThrow(() -> new IllegalStateException("Not found"))
// Transform if present
opt.map(String::toUpperCase) // Optional<"JAVA 8">
opt.flatMap(s -> Optional.of(s.length())) // Optional<6>
opt.filter(s -> s.startsWith("Java")) // Optional<"Java 8"> or empty
// Side effects
opt.ifPresent(System.out::println) // Print if present
opt.ifPresentOrElse(
s -> System.out.println("Found: " + s),
() -> System.out.println("Not found") // Java 9+
);Real-world Example
java exampleWoHoTech
// Old way — NullPointerException prone
String cityName = user.getAddress().getCity().getName();
// With Optional
Optional<String> city = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.map(City::getName);
String name = city.orElse("Unknown");Service layer example
java exampleWoHoTech
class UserService {
Optional<User> findById(int id) {
User user = repository.findById(id);
return Optional.ofNullable(user);
}
}
// Caller
userService.findById(5)
.map(User::getEmail)
.ifPresent(email -> sendEmail(email));Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Optional Class.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java topic.
Search Terms
java, java programming, core java, java master course, java notes, master, course, features
Related Java Topics
Continue learning this concept
Java 8 FeaturesJava 8 Date/Time APItitle: Date Time API in Java 8Java 8 FeaturesDefault aur Static Methods in Interfacetitle: Default and Static Methods in InterfaceJava 8 FeaturesFunctional Interfacetitle: Functional Interface in Java 8Java 8 FeaturesLambda Expressiontitle: Lambda Expression in Java 8Java 8 FeaturesMethod Referencetitle: Method Reference in Java 8Java 8 FeaturesStream APItitle: Stream API in Java 8