← Back to Advanced Java Course | Chapter 3: Functional Programming | Lesson 4 of 6

Java की Optional Class

Optional एक box है जिसमें एक value हो सकती है या नहीं, इसलिए आपको उपयोग से पहले जांचना चाहिए। यह किसी ऐसी चीज़ के उपयोग से आने वाले आम crash से बचने में मदद करता है जो मौजूद ही नहीं है।
Syntax
java
Optional<Type> optional = Optional.ofNullable(value);
optional.isPresent();
optional.orElse(defaultValue);
optional.ifPresent(value -> action);

What is Optional?

Optional class एक container object है जिसे specifically किसी value की मौजूदगी या अनुपस्थिति को represent करने के लिए डिज़ाइन किया गया है, बिना किसी bare null reference के उपयोग के। यह आपको missing values को सुरक्षित रूप से handle करने में मदद करता है और किसी method के return type में 'कोई value नहीं' की संभावना को, एक implicit, undocumented जोखिम होने के बजाय, दिखाई देने योग्य बनाता है।

उदाहरण: What is Optional?

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<String> name = Optional.of("Meera");
		// Optional wraps a value that may be absent
		Optional<String> empty = Optional.empty();
		// Print a line to the console
		System.out.println(name.isPresent() + " " + empty.isPresent());
	}
}

Checking Presence and Retrieving Values

आप isPresent() का उपयोग करके जांच सकते हैं कि किसी Optional के अंदर कोई value मौजूद है या नहीं, और सिर्फ तभी कुछ code चलाने के लिए जब कोई value वाकई मौजूद हो, इसके बजाय ifPresent() method का उपयोग करें, जो एक explicit if-check को पूरी तरह टाल देता है।

उदाहरण: Checking Presence and Retrieving Values

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<String> value = Optional.of("data");
		// Check whether value.isPresent()
		if (value.isPresent()) {
			// Print a line to the console
			System.out.println(value.get());
		}
		value.ifPresent(v -> System.out.println("Present: " + v));
	}
}

Safe Fallback Methods

आप Optional के खाली निकलने पर उपयोग करने के लिए एक fallback default provide कर सकते हैं, या तो orElse() का उपयोग करके, जो हमेशा default को eagerly compute करता है, या orElseGet() का उपयोग करके, जो सिर्फ तभी एक supplier के ज़रिए lazily इसे compute करता है जब वाकई ज़रूरत हो।

उदाहरण: Safe Fallback Methods

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<String> empty = Optional.empty();
		// Print a line to the console
		System.out.println(empty.orElse("default value"));
		// Print a line to the console
		System.out.println(empty.orElseGet(() -> "computed lazily"));
	}
}

Throwing Exceptions with Optional

अगर आप किसी missing value को सीधे तौर पर एक error माना जाना चाहते हैं, तो चुपचाप fallback करने के बजाय एक चुना हुआ exception फेंकने के लिए orElseThrow() method का उपयोग करें। यह आपको यह जांचने का एक साफ़, explicit तरीका देता है कि आगे बढ़ने से पहले एक optional input असल में प्रदान किया गया था।

उदाहरण: Throwing Exceptions with Optional

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<String> value = Optional.of("present");
		// Print a line to the console
		System.out.println(value.orElseThrow(() -> new IllegalStateException("missing value")));
	}
}

Transforming Optionals

आप filter() और map() का उपयोग करके किसी Optional के अंदर की value को transform कर सकते हैं, आपको conditions और conversions को एक pipeline में साथ chain करने देते हुए जो किसी भी step के fail होने पर अपने आप खाली में short-circuit हो जाता है — बहुत कुछ उसी भावना में जैसे एक Stream pipeline व्यवहार करता है।

उदाहरण: Transforming Optionals

java
// Import java.util.Optional so it can be used by its short name
import java.util.Optional;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Optional wraps a value that may be absent
		Optional<Integer> result = Optional.of(10)
			.filter(n -> n > 5)
			.map(n -> n * 2);
		// Print a line to the console
		System.out.println(result.get());
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. बिना जांचे opt.get() call करना, जो Optional के खाली होने पर NoSuchElementException फेंकता है; पहले orElse, ifPresent या isPresent का उपयोग करें।
  2. Optional.of(value) को ऐसी value के साथ उपयोग करना जो null हो सकती है, जो NullPointerException फेंकता है; Optional.ofNullable का उपयोग करें।
  3. orElse(expensiveCall()) लिखना, जो value मौजूद होने पर भी हमेशा call चलाता है; इसे सिर्फ ज़रूरत पड़ने पर चलाने के लिए orElseGet(() -> expensiveCall()) का उपयोग करें।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.