Monday, 16 May 2022

How for-each or enhanced for loop works in Java?

In this post, I am going to explain about for-each loop.

 

‘for-each’ is an enhanced version of for loop and provides a cleaner way to iterate over collections and arrays.

 

Let’s get comfortable by practising some examples.

 

Iterate over an array using for-each loop

Syntax

for (DataType ele : array) { 
    .....
    .....
}

 

Above snippet is equivalent to below ‘for’ loop version.

for (int i=0; i<arr.length; i++) 
{ 
    DataType ele = arr[i];
    .......
    .......
}

 

IterateOverArrayUsingForEachLoop.java

package com.sample.app;

public class IterateOverArrayUsingForEachLoop {

	public static void main(String[] args) {
		int[] arr = { 2, 3, 5, 7 };

		for (int ele : arr) {
			System.out.println(ele);
		}
	}

}

 

Output

2
3
5
7

 

Iterate over an List using for-each loop

Syntax

 

for (DataType ele : list) { 
    .....
    .....
}

 

Above snippet is equivalent to below ‘for’ loop version.

for(int i = 0; i < list.size(); i++) {
	DataType ele = list.get(i);
	......
	......
}

Find the below working application.

 

IterateOverListUsingForEachLoop.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class IterateOverListUsingForEachLoop {
	public static void main(String[] args) {
		List<Integer> list = Arrays.asList(2, 3, 5, 7);
		
		for(Integer ele: list) {
			System.out.println(ele);
		}
		
		for(int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
	}
}

Iterate over a map using for-each loop

Syntax

for(DataType key: map.keySet()) {
	DataType valye = map.get(key);
	.....
	.....
}

Find the below working application.

 

IterateOverAMapUsingForEachLoop.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

public class IterateOverAMapUsingForEachLoop {
	
	public static void main(String[] args) {
		Map<Integer, String> numbersMap = new HashMap<>();
		
		numbersMap.put(1, "One");
		numbersMap.put(2, "Two");
		numbersMap.put(3, "Three");
		
		for(Integer key: numbersMap.keySet()) {
			System.out.printf("%d --> %s\n", key, numbersMap.get(key));
		}
	}

}

Output

1 --> One
2 --> Two
3 --> Three

You can refer this post, to find different ways to iterate over a map using for-each loop.

 

Can I provide for-each behaviour to custom collection?

By implementing Iterable interface, we can provide for-each behaviour to a custom collection.

 

EvenIndicesList.java

package com.sample.app;

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class EvenIndicesList<T> implements Iterable<T> {
	private List<T> list;

	EvenIndicesList(List<T> list) {
		this.list = list;
	}

	public Iterator<T> iterator() {
		return new EvenIterator<T>();
	}

	@SuppressWarnings("hiding")
	private class EvenIterator<T> implements Iterator<T> {
		int size = list.size();
		int currentPointer = 0;

		public boolean hasNext() {
			return (currentPointer < size);
		}

		public T next() {
			if (!hasNext()) {
				throw new NoSuchElementException();
			}

			@SuppressWarnings("unchecked")
			T val = (T) list.get(currentPointer);
			currentPointer += 2;

			return val;
		}

	}

}

‘EvenIndicesList’ class print the elements at even indexes while iterate using for-each loop. Let’s test this behaviour.

 

TestEvenList.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class TestEvenList {
	public static void main(String args[]) {
		List<Integer> list = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19);

		EvenIndicesList<Integer> myList = new EvenIndicesList(list);

		for (int i : myList) {
			System.out.println(i);
		}
	}
}

Output

2
5
11
17


 

 You may like

Interview Questions

Jagged arrays in Java

Get the length of longest row in a two dimensional jagged array in Java

Quick guide to OutOfMemoryError in Java

StackOverFlowError vs OutOfMemoryError in Java

Different ways to iterate over a map using for-each loop

Different ways to iterate over a map using for-each loop

In this post, I am going explain the two approaches to iterate over a map using for-each loop.

 

Approach 1: for-each loop with Map entrySet

for (Map.Entry<Integer, String> entry : numbersMap.entrySet()) {
	System.out.printf("%d --> %s\n", entry.getKey(), entry.getValue());
}

 

Approach 2L for-each loop with Map keyset.

for (Integer key : numbersMap.keySet()) {
	System.out.printf("%d --> %s\n", key, numbersMap.get(key));
}

 

Find the below working application.

 

ForEachMapDemo.java

package com.sample.app;

import java.util.HashMap;
import java.util.Map;

public class ForEachMapDemo {

	public static void main(String[] args) {
		Map<Integer, String> numbersMap = new HashMap<>();

		numbersMap.put(1, "One");
		numbersMap.put(2, "Two");
		numbersMap.put(3, "Three");

		// Approach 1
		for (Map.Entry<Integer, String> entry : numbersMap.entrySet()) {
			System.out.printf("%d --> %s\n", entry.getKey(), entry.getValue());
		}

		System.out.println("\n\n");

		// Approach 2
		for (Integer key : numbersMap.keySet()) {
			System.out.printf("%d --> %s\n", key, numbersMap.get(key));
		}
	}

}

 

Output

1 --> One
2 --> Two
3 --> Three



1 --> One
2 --> Two
3 --> Three

   

 You may like

Interview Questions

How to resolve NoClassDefFoundError?

Jagged arrays in Java

Get the length of longest row in a two dimensional jagged array in Java

Quick guide to OutOfMemoryError in Java

StackOverFlowError vs OutOfMemoryError in Java

StackOverFlowError vs OutOfMemoryError in Java

In this post, I am going to explain the difference between StackOverFlowError and OutOfMemoryError. Let’s try to understand what is stack and Heap before dig further.

 

Stack and Heap memory

Stack is a special region in computer memory, that stores temporary variables like local variables, parameters, function calls etc., Stack works in last in first out (LIFO) order. Whenever a new local variable initialized inside a function, it is pushed onto the stack, when the function finished execution, all the local variables pushed by that function onto the stack are removed from the stack. Read this post  for more details.

 

Heap is a portion of memory where dynamic allocation and de allocations happen. When the application request for a new object, JVM allocates the memory in Heap. Heap memory is slightly slower to read from and written to, because pointer access is needed to access heap memory. The JVM allocates Java heap memory from the OS and then manages the heap for the Java application. Refer this post for more details.

 

StackOverflowError

StackOverflowError is related to stack memory area and it is thrown when a stack overflow occurs because an application recurses too deeply.

 


 

Let’s try to produce StackOverflowError.

 

StackOverflowErrorDemo.java

public class StackOverflowErrorDemo {

	static void fun() {
		fun();
	}

	public static void main(String args[]) {
		fun();
	}
}

 

Compile and run above application.

$javac StackOverflowErrorDemo.java 
$
$java StackOverflowErrorDemo
Exception in thread "main" java.lang.StackOverflowError
	at StackOverflowErrorDemo.fun(StackOverflowErrorDemo.java:4)
	at StackOverflowErrorDemo.fun(StackOverflowErrorDemo.java:4)
	at StackOverflowErrorDemo.fun(StackOverflowErrorDemo.java:4)
	at StackOverflowErrorDemo.fun(StackOverflowErrorDemo.java:4)
	at StackOverflowErrorDemo.fun(StackOverflowErrorDemo.java:4)
	at StackOverflowErrorDemo.fun(StackOverflowErrorDemo.java:4)
	at StackOverflowErrorDemo.fun(StackOverflowErrorDemo.java:4)

 

As you see the class ‘StackOverflowErrorDemo’, ‘fun()’ method calls itself recursively infinite times, which leads to the stack gets exhausted and endup in StackOverflowError.

 

How to resolve StackOverflowError?

a. Check your application code for infinite recursions and resolve them.

 

b. If there is no infinite recursion, try increasing the stack size. Refer this post to increase the stack size.

 

OutOfMemoryError

OutOfMemoryError Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.



OutOfMemoryError is related to Java Heapmemory. It typically occur, when the application request memory for a new object, but the heap is already full.

 

Let’s write a simple program to produce OutOfMemoryError.

 

OutOfMemoryErrorDemo.java

public class OutOfMemoryErrorDemo {

	public static void main(String[] args) {
		Integer obj[] = new Integer[Integer.MAX_VALUE];

		for (int i = 0; i < Integer.MAX_VALUE; i++)
			obj[i] = i;

		System.out.println("I am done");
	}

}

 

Compile and run the above program.

$javac OutOfMemoryErrorDemo.java 
$
$java OutOfMemoryErrorDemo
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
	at OutOfMemoryErrorDemo.main(OutOfMemoryErrorDemo.java:4)

 

How to address the OutOfMemoryError?

a. First Profile your application and try to figure out, is your application referring any unused objects, or is there any memory leaks etc., You can refer this post to find the tools to analyze your java application.

 

b. Increase the heap size. Refer this post for more details.

 

 

References

https://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html

https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html

 

 

 You may like

Interview Questions

Implement map using array as storage

How to resolve NoClassDefFoundError?

Jagged arrays in Java

Get the length of longest row in a two dimensional jagged array in Java

Quick guide to OutOfMemoryError in Java