Java को स्वचालित रूपान्तरण हो (, ) र तिनका (, ) को बीचमा। यो सुविधाजनक छ तर सूक्ष्म क्षति हरु छन् — performance overhead, आश्चर्यजनक व्यवहार, र को जोखिम।
intdoubleIntegerDouble==NullPointerExceptionInteger boxed = 42; // autoboxing: int → Integer (Integer.valueOf(42))
int unboxed = boxed; // auto-unboxing: Integer → int (boxed.intValue())
List<Integer> nums = new ArrayList<>();
nums.add(5); // autoboxes int 5 → Integer (collections need objects)
int x = nums.get(0); // auto-unboxes Integer → int
यो स्वचालित रूपमा हुन्छ किनभने collections र generics लाई objects चाहिन्छ (तपाईंसँग List<int> हुन सक्दैन), त्यसैले Java primitives लाई पारदर्शी रूपमा box गर्छ।
Integer a = 1000;
Integer b = 1000;
a == b; // ❌ FALSE — different Integer OBJECTS (reference comparison)
a.equals(b); // ✅ true — value comparison
// the WORSE trap — the Integer cache makes small values seem to work:
Integer c = 100, d = 100;
c == d; // TRUE — Java CACHES Integers from -128 to 127 (same object)
Integer e = 200, f = 200;
e == f; // FALSE — outside the cache range → different objects
यो चिन्ताजनक छ: Integer मा == सानो मानहरुको लागि काम गर्छ (cached) तर ठूलो मानहरुको लागि असफल हुन्छ — परीक्षणमा सही देखिने कोड उत्पादनमा विच्छेद हुन्छ। Wrapper value तुलनाको लागि सधैँ .equals() प्रयोग गर्नुहोस्, वा पहिले primitives लाई unbox गर्नुहोस्।
Integer value = null; // a wrapper can be null
int x = value; // 💥 NullPointerException — unboxing null calls null.intValue()
Map<String, Integer> map = new HashMap<>();
int count = map.get("missing"); // 💥 NPE — get() returns null, then unboxing fails
Wrapper लाई null unbox गर्दा NPE फेकिन्छ — एक साधारण, आश्चर्यजनक क्रास, विशेष गरी map lookups को साथ जो null फिर्ता गर्छन्।
// ❌ autoboxing in a hot loop — creates millions of Integer objects (GC pressure, slow)
Long sum = 0L; // WRONG type — wrapper
for (long i = 0; i < 1_000_000; i++) {
sum += i; // unbox, add, re-box → new Long each iteration!
}
// ✅ use primitives in hot paths
long sum = 0L; // primitive — no boxing
दोहोरिने boxing/unboxing ले अत्यधिक objects सिर्जना गर्छ, tight loops मा performance लाई हानी गर्छ।
Autoboxing सुविधाजनक र व्यापक छ (collections, generics सबै यस मा निर्भर गर्छन्), तर यसका क्षति हरु वास्तविक, कठिन-निदान गरिने bugs को कारण बनाउँछन्।
== trap विशेष गरी खतरनाक छ: Integer हरु को साथ == को तुलना cached सानो मानहरुको लागि काम गर्छ (-128 to 127) तर ठूलो मानहरुको लागि चुपचाप असफल हुन्छ — एक bug जो परीक्षण पास गर्छ र उत्पादनमा विच्छेद हुन्छ — wrapper तुलनाको लागि .equals() (वा unboxing) आवश्यक बनाउँछ। NullPointerExceptions null wrappers (map lookups को साथ साधारण) को unboxing मा अर्को बारम्बार क्रास हुन्।
र boxing hot loops मा अनावश्यक objects सिर्जना गर्छ, performance लाई हानी गर्छ।
Boxing कहिले हुन्छ, value-vs-reference तुलना समस्या, null-unboxing जोखिम, र performance-critical code मा primitives प्रयोग गर्दा बुझ्नु सही, कुशल Java लेख्नको लागि महत्त्वपूर्ण छ — र Integer-cache == व्यवहार एक क्लासिक साक्षात्कार प्रश्न हो जो गहिरो बुझाइ प्रकट गर्छ।