PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम for Loop and Enhanced for-each Loop in Java (for लूप और संवर्धित for-each लूप (कलेक्शंस व एरे के लिए)) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।
Overview: The standard for loop in Java provides explicit index-based iteration with separate initialization, boolean termination condition, and update clauses. Introduced in Java 5, the enhanced for-each loop simplifies read-only sequential traversal over arrays and objects implementing java.lang.Iterable.
अध्याय सार: जावा में मानक for लूप अलग-अलग इनिशियलाइज़ेशन, बूलियन कंडीशन और अपडेट क्लॉज़ के साथ इंडेक्स-आधारित इटरेशन प्रदान करता है। जावा 5 में शामिल किया गया संवर्धित for-each लूप एरे और java.lang.Iterable लागू करने वाले कलेक्शंस के क्रमिक ट्रैवर्सल को सरल बनाता है।
for Loop and Enhanced for-each Loop in Java: Detailed Notes & Architecture (for लूप और संवर्धित for-each लूप (कलेक्शंस व एरे के लिए))
1. Anatomy and Execution Flow of Standard for Loop (मानक for लूप की संरचना और निष्पादन क्रम)
[EN] A standard for loop follows the syntax for(initialization; condition; update) where all three expressions are optional. Initialization runs exactly once before the loop starts and may declare multiple variables of the same data type separated by commas. The boolean condition is evaluated before every iteration; if omitted, it defaults to true and creates an infinite loop such as for(;;). After the loop body executes, the update clause runs and control returns to the condition check.
[HI] मानक for लूप का सिंटैक्स for(initialization; condition; update) होता है जिसमें तीनों एक्सप्रेशन वैकल्पिक होते हैं। इनिशियलाइज़ेशन लूप शुरू होने से पहले केवल एक बार चलता है और इसमें कॉमा से अलग करके एक ही डेटा टाइप के कई वेरिएबल घोषित किए जा सकते हैं। प्रत्येक इटरेशन से पहले बूलियन कंडीशन जांची जाती है; यदि इसे छोड़ दिया जाए, तो यह डिफ़ॉल्ट रूप से true मानी जाती है और for(;;) जैसा अनंत लूप बनाती है। लूप बॉडी चलने के बाद अपडेट क्लॉज़ निष्पादित होता है और नियंत्रण वापस कंडीशन जांच पर लौटता है।
2. Enhanced for-each Loop Mechanics and Target Types (संवर्धित for-each लूप की कार्यप्रणाली और लक्ष्य प्रकार)
[EN] Introduced in J2SE 5.0 (JSR 201), the enhanced for-each loop uses the syntax for(Type element : collectionOrArray). The compiler translates a for-each loop over an array into a standard index-counter loop using arr.length. When iterating over a collection, the compiler converts it into calls to java.util.Iterator using iterator(), hasNext(), and next(). Therefore, any custom class must implement the java.lang.Iterable interface to work with the enhanced for-each statement.
[HI] J2SE 5.0 (JSR 201) में पेश किए गए संवर्धित for-each लूप का सिंटैक्स for(Type element : collectionOrArray) होता है। कंपाइलर एरे पर चलने वाले for-each लूप को आंतरिक रूप से arr.length का उपयोग करने वाले मानक इंडेक्स-काउंटर लूप में बदल देता है। किसी कलेक्शन पर इटरेशन करते समय कंपाइलर इसे iterator(), hasNext() और next() मेथड्स के साथ java.util.Iterator कॉल में परिवर्तित करता है। अतः किसी भी कस्टम क्लास को for-each के साथ उपयोग करने के लिए java.lang.Iterable इंटरफ़ेस इम्प्लीमेंट करना आवश्यक होता है।
3. Limitations of Enhanced for-each vs Standard for (मानक for की तुलना में संवर्धित for-each लूप की सीमाएं)
[EN] The enhanced for-each loop always iterates strictly forward from the first element to the last, so reverse traversal is impossible without manual reversing. It does not expose the current element index, making tasks like comparing adjacent elements or tracking positions awkward. Assigning a new value to the loop variable modifies only the local copy, leaving primitive arrays and object references inside the source array unchanged. Additionally, adding or removing elements from a Collection directly inside a for-each loop triggers a fail-fast ConcurrentModificationException.
[HI] संवर्धित for-each लूप हमेशा पहले तत्व से अंतिम तत्व तक केवल आगे की दिशा में ही चलता है, इसलिए रिवर्स ट्रैवर्सल संभव नहीं है। यह वर्तमान तत्व का इंडेक्स उपलब्ध नहीं कराता, जिससे आसन्न तत्वों की तुलना या स्थिति ट्रैक करना कठिन होता है। लूप वेरिएबल को नया मान देने से केवल लोकल कॉपी बदलती है, जबकि मूल एरे के प्रिमिटिव मान या ऑब्जेक्ट रेफरेंस अपरिवर्तित रहते हैं। इसके अलावा, for-each लूप के भीतर सीधे कलेक्शन से तत्व जोड़ने या हटाने पर fail-fast ConcurrentModificationException उत्पन्न होता है।
4. Scope, Infinite Loops, and Compile-Time Rules (स्कोप, अनंत लूप और कंपाइल-टाइम नियम)
[EN] A loop variable declared in the for-loop header or in the for-each declaration is strictly scoped to that loop block and cannot be accessed outside. In Java, declaring for(int i = 0, long j = 0; ...) causes a compile-time error because mixed data types are disallowed in the initialization clause. Unlike C or C++, Java requires the termination expression to evaluate strictly to boolean; integers like 1 or 0 produce a type mismatch error. Using a null reference as the target expression in a for-each loop compiles cleanly but throws NullPointerException at runtime.
[HI] for लूप हेडर या for-each घोषणा में बना लूप वेरिएबल केवल उसी लूप ब्लॉक तक सीमित (scoped) रहता है और बाहर एक्सेस नहीं किया जा सकता। जावा में for(int i = 0, long j = 0; ...) लिखने पर कंपाइल-टाइम एरर आती है क्योंकि इनिशियलाइज़ेशन क्लॉज़ में अलग-अलग डेटा टाइप की अनुमति नहीं है। C या C++ के विपरीत, जावा में कंडीशन एक्सप्रेशन का परिणाम अनिवार्य रूप से boolean होना चाहिए; 1 या 0 जैसे पूर्णांक टाइप मिसमैच एरर देते हैं। for-each लूप के लक्ष्य के रूप में null रेफरेंस पास करने पर कोड कंपाइल हो जाता है लेकिन रनटाइम पर NullPointerException आता है।
Syntax, Formula & Technical Example (for Loop and Enhanced for-each Loop in Java)
int[] scores = {75, 88, 92, 64};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total += scores[i];
}
for (int val : scores) {
System.out.print(val + " ");
}
System.out.println("Total = " + total);
for Loop and Enhanced for-each Loop in Java Quick Reference & Comparison Table
| Loop Construct | Key Mechanism | Exam Fact |
|---|---|---|
| Standard for Loop | Explicit init, boolean test, and step expression | Supports reverse iteration and direct index manipulation |
| Enhanced for-each | Internal Iterator or hidden array counter | Introduced in Java 5; requires array or Iterable target |
| Infinite for(;;) | Omitted condition defaults to boolean true | Terminates only via break, return, or thrown exception |
| Comma-Separated Init | Multiple variables of single identical data type | Mixing int and long in header fails compilation |
for Loop and Enhanced for-each Loop in Java Top 20 Bilingual MCQs with Answers
Q1. In which version of Java was the enhanced for-each loop introduced?
(जावा के किस संस्करण में संवर्धित for-each लूप को पेश किया गया था?)
(A) Java 5 (J2SE 5.0)
(B) Java 7
(C) Java 1.2
(D) Java 8
Correct Answer: (A)
[EN] The enhanced for-each loop was added in J2SE 5.0 (Java 5) under JSR 201 alongside generics.
[HI] संवर्धित for-each लूप को जेनेरिक्स के साथ J2SE 5.0 (जावा 5) में JSR 201 के तहत जोड़ा गया था।
Q2. Which interface must a custom class implement so its instances can be used as the target of an enhanced for-each loop?
(किसी कस्टम क्लास के ऑब्जेक्ट को for-each लूप के लक्ष्य के रूप में उपयोग करने के लिए उसे कौन-सा इंटरफ़ेस इम्प्लीमेंट करना आवश्यक है?)
(A) java.lang.Comparable
(B) java.io.Serializable
(C) java.util.Iterator
(D) java.lang.Iterable
Correct Answer: (D)
[EN] A class must implement java.lang.Iterable (which returns an Iterator) to support the enhanced for-each loop.
[HI] for-each लूप का समर्थन करने के लिए क्लास को java.lang.Iterable इम्प्लीमेंट करना होता है जो Iterator लौटाता है।
Q3. What happens when you compile and run: for(;;) { System.out.print("A"); break; }?
(कोड for(;;) { System.out.print("A"); break; } को कंपाइल और रन करने पर क्या होगा?)
(A) Prints A once and terminates normally
(B) Prints A infinitely without stopping
(C) Compile-time syntax error due to empty clauses
(D) Throws IllegalStateException at runtime
Correct Answer: (A)
[EN] An omitted condition in for(;;) defaults to true, prints A once, and break exits the loop immediately.
[HI] for(;;) में कंडीशन न होने पर वह true मानी जाती है, एक बार A प्रिंट होता है और break लूप से बाहर कर देता है।
Q4. What exception is thrown if a collection is structurally modified (element removed directly via list.remove) inside a standard Collection for-each loop?
(सामान्य Collection के for-each लूप के अंदर सीधे list.remove() द्वारा संरचना बदलने पर कौन-सा एक्सेप्शन आता है?)
(A) ConcurrentModificationException
(B) UnsupportedOperationException
(C) IllegalMonitorStateException
(D) IndexOutOfBoundsException
Correct Answer: (A)
[EN] Standard fail-fast iterators used internally by for-each throw ConcurrentModificationException upon structural modification.
[HI] for-each द्वारा आंतरिक रूप से प्रयुक्त fail-fast इटररेटर संरचनात्मक बदलाव होने पर ConcurrentModificationException फेंकते हैं।
Q5. Consider: int[] a = {1, 2, 3}; for (int x : a) { x = x * 10; } What are the contents of array a afterwards?
(यदि int[] a = {1, 2, 3}; for (int x : a) { x = x * 10; } चलाया जाए, तो लूप के बाद एरे a के तत्व क्या होंगे?)
(A) {0, 0, 0}
(B) {10, 20, 30}
(C) Compile-time error because x is final
(D) {1, 2, 3}
Correct Answer: (D)
[EN] The loop variable x receives a copy of each primitive element, so modifying x does not alter array a.
[HI] लूप वेरिएबल x को प्रत्येक प्रिमिटिव तत्व की कॉपी मिलती है, इसलिए x बदलने से मूल एरे a नहीं बदलता।
Q6. Which for-loop header will fail to compile in Java?
(जावा में निम्न में से कौन-सा for-लूप हेडर कंपाइल होने में विफल रहेगा?)
(A) for (System.out.println("Start"); false; )
(B) for (; i < 5; )
(C) for (int i = 0, double j = 1.0; i < 5; i++)
(D) for (int i = 0, j = 10; i < j; i++, j--)
Correct Answer: (C)
[EN] Java allows multiple variables in the initialization clause only if they share the exact same data type.
[HI] जावा इनिशियलाइज़ेशन क्लॉज़ में कई वेरिएबल तभी स्वीकार करता है जब उनका डेटा टाइप समान हो।
Q7. In a standard for(init; cond; update) loop, how many times is the initialization expression executed?
(मानक for(init; cond; update) लूप में इनिशियलाइज़ेशन एक्सप्रेशन कितनी बार निष्पादित होता है?)
(A) Once before the first condition check
(B) After every iteration
(C) Before every iteration
(D) Zero times if the condition is true
Correct Answer: (A)
[EN] Initialization runs strictly once at loop entry prior to evaluating the loop condition.
[HI] लूप में प्रवेश करते समय इनिशियलाइज़ेशन कंडीशन की पहली जांच से पहले केवल एक बार चलता है।
Q8. What happens if you pass a null array reference to an enhanced for-each loop like int[] arr = null; for(int x : arr) {}?
(यदि int[] arr = null; for(int x : arr) {} चलाया जाए तो क्या परिणाम होगा?)
(A) Throws NullPointerException at runtime
(B) Compile-time null safety error
(C) Zero iterations and normal continuation
(D) Prints default 0 once
Correct Answer: (A)
[EN] The enhanced for-each loop attempts to read arr.length or call iterable.iterator(), raising NullPointerException.
[HI] for-each लूप arr.length पढ़ने या iterator() कॉल करने का प्रयास करता है जिससे रनटाइम पर NullPointerException आता है।
Q9. What output does this snippet produce? int s = 0; for(int i = 1; i <= 4; i++) { s += i; } System.out.print(s);
(यह कोड क्या आउटपुट देगा? int s = 0; for(int i = 1; i <= 4; i++) { s += i; } System.out.print(s);)
(A) 15
(B) 4
(C) 10
(D) 6
Correct Answer: (C)
[EN] The loop sums 1 + 2 + 3 + 4 = 10 before i increments to 5 and terminates.
[HI] लूप 1 + 2 + 3 + 4 = 10 का योग करता है और i = 5 होने पर समाप्त हो जाता है।
Q10. Which statement is legally valid in the update expression of a standard Java for loop?
(मानक जावा for लूप के अपडेट एक्सप्रेशन में कौन-सा कथन वैध है?)
(A) New local variable declarations like int k = 1
(B) Method calls and assignment expressions separated by commas
(C) Multiple boolean conditions joined by semicolons
(D) Import statements
Correct Answer: (B)
[EN] The update section accepts any comma-separated list of expression statements such as increments or method calls.
[HI] अपडेट सेक्शन कॉमा से अलग किए गए एक्सप्रेशन स्टेटमेंट्स जैसे इंक्रीमेंट या मेथड कॉल्स को स्वीकार करता है।
Q11. Why is an index-based standard for loop preferred over for-each when reversing an array in-place?
(किसी एरे को इन-प्लेस रिवर्स करते समय for-each की तुलना में इंडेक्स-आधारित मानक for लूप को प्राथमिकता क्यों दी जाती है?)
(A) for-each cannot traverse backwards or track indices for swapping
(B) for-each uses twice as much CPU cache
(C) Standard for loops bypass array bounds checking
(D) for-each works only with String objects
Correct Answer: (A)
[EN] In-place swapping needs direct access to start and end indices simultaneously, which for-each does not expose.
[HI] इन-प्लेस स्वैपिंग के लिए शुरुआती और अंतिम दोनों इंडेक्स का सीधा एक्सेस चाहिए जो for-each में उपलब्ध नहीं होता।
Q12. What is the compile-time error in: for(int i = 0; 1; i++) {}?
(कोड for(int i = 0; 1; i++) {} में कंपाइल-टाइम एरर क्यों आती है?)
(A) Variable i is uninitialized
(B) Missing update expression
(C) Infinite loop detected by javac
(D) Incompatible types: int cannot be converted to boolean
Correct Answer: (D)
[EN] Unlike C/C++, Java strictly requires a boolean expression in the loop termination condition.
[HI] C/C++ के विपरीत जावा में लूप की टर्मिनेशन कंडीशन का टाइप अनिवार्य रूप से boolean होना चाहिए।
Q13. In Java, what is the scope of variable i declared as for(int i = 0; i < 3; i++) {}?
(जावा में for(int i = 0; i < 3; i++) {} में घोषित वेरिएबल i का स्कोप क्या होता है?)
(A) Accessible only inside the update clause
(B) Accessible only inside the for loop header and body
(C) Accessible as a class static field
(D) Accessible throughout the enclosing method
Correct Answer: (B)
[EN] Variables declared in a for-loop header remain strictly local to that loop's execution block.
[HI] for-लूप हेडर में घोषित वेरिएबल केवल उसी लूप के ब्लॉक और बॉडी के भीतर ही सुलभ रहते हैं।
Q14. Which of the following is NOT true about the enhanced for-each loop in Java?
(जावा में संवर्धित for-each लूप के बारे में निम्न में से कौन-सा कथन सत्य नहीं है?)
(A) It iterates sequentially from start to end
(B) It allows updating primitive array elements directly through the loop variable
(C) It works with both primitive arrays and generic Collections
(D) It reduces off-by-one index errors
Correct Answer: (B)
[EN] Reassigning the for-each variable only updates a temporary local copy, never the underlying primitive array slot.
[HI] for-each वेरिएबल को नया मान देने से केवल लोकल कॉपी बदलती है, मूल प्रिमिटिव एरे का मान नहीं।
Q15. What will this code print? for(int i = 0; i < 3; System.out.print(i++)) {}
(यह कोड क्या प्रिंट करेगा? for(int i = 0; i < 3; System.out.print(i++)) {})
(A) Compile-time error
(B) 123
(C) 012
(D) 0123
Correct Answer: (C)
[EN] Post-increment passes 0, 1, and 2 to print during each update step before i becomes 3 and fails i < 3.
[HI] पोस्ट-इंक्रीमेंट अपडेट चरण में क्रमशः 0, 1 और 2 प्रिंट करता है, फिर i = 3 होने पर कंडीशन असत्य हो जाती है।
Q16. How does the Java compiler implement an enhanced for-each loop when traversing an int[] array?
(किसी int[] एरे को ट्रैवर्स करते समय जावा कंपाइलर for-each लूप को आंतरिक रूप से कैसे लागू करता है?)
(A) By spawning a parallel ForkJoinPool thread
(B) By wrapping every int in an Integer Iterator
(C) By rewriting it into an indexed loop using array.length
(D) By cloning the entire array before iteration
Correct Answer: (C)
[EN] For arrays, javac generates bytecode equivalent to a traditional counter loop iterating up to array.length without boxing overhead.
[HI] एरे के लिए javac बिना बॉक्सिंग ओवरहेड के array.length तक चलने वाले पारंपरिक काउंटर लूप जैसा बाइटकोड जनरेट करता है।
Q17. Within for Loop and Enhanced for-each Loop in Java, which loop construct directly maps to: "Explicit init, boolean test, and step expression"?
(for Loop and Enhanced for-each Loop in Java में कौन सा Loop Construct सीधे "Explicit init, boolean test, and step expression" से संबंधित है?)
(A) Infinite for(;;)
(B) Standard for Loop
(C) Comma-Separated Init
(D) Enhanced for-each
Correct Answer: (B)
[EN] In for Loop and Enhanced for-each Loop in Java, 'Standard for Loop' handles 'Explicit init, boolean test, and step expression' (Supports reverse iteration and direct index manipulation).
[HI] for Loop and Enhanced for-each Loop in Java में 'Standard for Loop' का कार्य/विवरण 'Explicit init, boolean test, and step expression' (Supports reverse iteration and direct index manipulation) है।
Q18. Which option accurately describes 'Enhanced for-each' in for Loop and Enhanced for-each Loop in Java?
(for Loop and Enhanced for-each Loop in Java के संदर्भ में 'Enhanced for-each' की सही विशेषता कौन सी है?)
(A) Explicit init, boolean test, and step expression
(B) Omitted condition defaults to boolean true
(C) Multiple variables of single identical data type
(D) Internal Iterator or hidden array counter
Correct Answer: (D)
[EN] 'Enhanced for-each' provides 'Internal Iterator or hidden array counter' — key point: Introduced in Java 5; requires array or Iterable target.
[HI] 'Enhanced for-each' का मुख्य विवरण 'Internal Iterator or hidden array counter' है (Introduced in Java 5; requires array or Iterable target)।
Q19. In for Loop and Enhanced for-each Loop in Java, identify the correct parameter for the specification: "Omitted condition defaults to boolean true".
(for Loop and Enhanced for-each Loop in Java में "Omitted condition defaults to boolean true" विवरण किस विकल्प के लिए सही है?)
(A) Comma-Separated Init
(B) Standard for Loop
(C) Infinite for(;;)
(D) Enhanced for-each
Correct Answer: (C)
[EN] 'Infinite for(;;)' corresponds to 'Omitted condition defaults to boolean true' (Terminates only via break, return, or thrown exception).
[HI] 'Infinite for(;;)' का संबंध 'Omitted condition defaults to boolean true' (Terminates only via break, return, or thrown exception) से है।
Q20. Considering for Loop and Enhanced for-each Loop in Java, what key behavior defines 'Comma-Separated Init'?
(for Loop and Enhanced for-each Loop in Java में 'Comma-Separated Init' की मुख्य भूमिका या मान क्या है?)
(A) Multiple variables of single identical data type
(B) Omitted condition defaults to boolean true
(C) Explicit init, boolean test, and step expression
(D) Internal Iterator or hidden array counter
Correct Answer: (A)
[EN] 'Comma-Separated Init' represents 'Multiple variables of single identical data type' (Mixing int and long in header fails compilation).
[HI] 'Comma-Separated Init' का अर्थ/मान 'Multiple variables of single identical data type' है (Mixing int and long in header fails compilation)।
for Loop and Enhanced for-each Loop in Java — Exam FAQs
Q1: Can an enhanced for-each loop iterate over a Map directly in Java?
क्या जावा में संवर्धित for-each लूप सीधे किसी Map पर इटरेशन कर सकता है?
[EN] No. java.util.Map does not extend Iterable, so you must iterate over map.entrySet(), map.keySet(), or map.values().
[HI] नहीं। java.util.Map इंटरफ़ेस Iterable को एक्सटेंड नहीं करता, इसलिए आपको map.entrySet(), map.keySet() या map.values() पर इटरेशन करना होगा।
Q2: Is the enhanced for-each loop faster than a standard for loop?
क्या संवर्धित for-each लूप मानक for लूप से तेज़ होता है?
[EN] For arrays and ArrayList, performance is virtually identical because javac compiles array for-each to an index loop; for LinkedList, for-each with Iterator avoids O(n^2) get(i) overhead.
[HI] एरे और ArrayList के लिए गति लगभग समान होती है; लेकिन LinkedList में Iterator का उपयोग करने वाला for-each लूप इंडेक्स get(i) के O(n^2) ओवरहेड से बचाता है।
Q3: Can we modify an object's fields inside a for-each loop?
क्या हम for-each लूप के अंदर किसी ऑब्जेक्ट के फ़ील्ड्स को बदल सकते हैं?
[EN] Yes. While reassigning the loop variable does not replace the array element, invoking setter methods on the referenced object mutates that object's internal state.
[HI] हाँ। यद्यपि लूप वेरिएबल को नया रेफरेंस देने से एरे तत्व नहीं बदलता, लेकिन रेफरेंस किए गए ऑब्जेक्ट के सेटर मेथड कॉल करके उसके आंतरिक डेटा को बदला जा सकता है।
Post a Comment
Post a Comment