Friday, May 8, 2026

How to Loop Through a Map in Java

When working with collections, one common requirement is iterating over a Map implementation such as HashMap or Treemap in Java. Understanding how to loop through a Map in Java is essential for tasks like processing key‑value pairs, transforming data, or building efficient algorithms.

Methods for Iterating a Map

The Map interface provides three key methods to loop or iterate any Map implementation.

  • Set<Map.Entry<K, V>> entrySet()- This method returns a set of key‑value pairs. The entries in the set are actually object of type Map.Entry.
  • Set<K> keySet()- This method returns a set that contains all keys in the map.
  • Collection<V> values()- This method returns a Collection view of all values in the map.

These methods allow you to choose whether you want to iterate over entries, keys, or values. Let's see how these methods can be used to loop through a HashMap in Java.

  1. You can use either an iterator or a For-Each loop to iterate through a Map. See example.
  2. Java 8 onwards you can also use forEach statement. See example.

HashMap iteration using for-each and iterator Java example

In the example code HashMap is used to demonstrate traversal of a Map.

public class HashMapLooping {

 /**
  * @param args
  */
  public static void main(String[] args) {
     // Setting up a HashMap
  Map<String, String> cityMap = new HashMap<String, String>();
  cityMap.put("1","New York City" );
  cityMap.put("2", "New Delhi");
  cityMap.put("3", "Newark");
  cityMap.put("4", "Newport");
  
  System.out.println("Looping with keySet");
  // Loop through HashMap using Key Set
  Set<String> citySet =  cityMap.keySet();
  for(String key : citySet){
   System.out.println("Key is " + key + " Value is " + cityMap.get(key));
  }
  
  System.out.println("Looping HashMap using entrySet");
  // Second way with entrySet
  for(Map.Entry<String, String> entry:  cityMap.entrySet()){
   System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
  }
  
  System.out.println("Looping with entrySet using Iterator");
  //Third way with iterator
  Iterator<Entry<String, String>> itr = cityMap.entrySet().iterator();
  while(itr.hasNext()){
   Map.Entry<String, String> entry = itr.next();
   System.out.println("Key is " + entry.getKey() + " Value is " + entry.getValue());
  }

  System.out.println("Looping HashMap using values method");
  for(String value : cityMap.values()){
    System.out.println("Value is " + value);
  }
 }
}

It can be seen that the first iteration of the HashMap is done using the keySet() method which gives a set of keys in the map. Using those keys respective values are retrieved. Since another call is required to get the mapped values this way of looping a HashMap is less efficient in case you need both keys and values.

Second iteration of the map is done using the entrySet() method which returns a set containing the Map.Entry objects. From Map.Entry object key and value can be retrieved using getKey() and getValue() methods.

Third way of iteration is again using the entrySet() method, only difference is instead of using the For-Each loop, iterator is used here.

Fourth way of iterating a HashMap uses the values() method and gives all the values stored in the HashMap.

Output of the program

Looping with keySet
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Looping HashMap using entrySet
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Looping with entrySet using Iterator
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Looping using values method
Value is New York City
Value is New Delhi
Value is Newark
Value is Newport
Value is Kolkata

Iterating HashMap using forEach in Java

From Java 8 onward, the forEach method was introduced as part of the Map interface, allowing developers to iterate over a HashMap in a clean, functional style. Combined with lambda expressions and method references, this approach reduces iteration to a single, expressive statement. With forEach statement you can even iterate a HashMap directly without getting a collection view of the Map.

public class HashMapLooping {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // Setting up a HashMap
  Map<String, String> cityMap = new HashMap<String, String>();
  cityMap.put("1","New York City" );
  cityMap.put("2", "New Delhi");
  cityMap.put("3", "Newark");
  cityMap.put("4", "Newport");
  
  System.out.println("Looping with Lambda expression forEach stmt"); 
  Set<Map.Entry<String, String>> valueSet = cityMap.entrySet();
  valueSet.forEach((a)->System.out.println("Key is " + a.getKey() + 
           " Value is " + a.getValue()));
  
  System.out.println("Looping with method reference forEach");
  cityMap.entrySet().forEach(System.out::println);
  // Looping HashMap directly with forEach
  System.out.println("Looping HashMap with forEach statement");
  cityMap.forEach((K,V)->System.out.println("Key is " + K + " Value is " + V));
 }
}

Output

Looping with Lambda expression forEach stmt
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Looping with method reference forEach
1=New York City
2=New Delhi
3=Newark
4=Newport
Looping HashMap with forEach statement
Key is 1 Value is New York City
Key is 2 Value is New Delhi
Key is 3 Value is Newark
Key is 4 Value is Newport
Key is 5 Value is Kolkata

đź’ĄPoints to note

  • A map can be iterated using entrySet() which returns a set containing objects of type Map.Entry.
  • Another way to iterate a map in Java is using keySet() method which returns a set containing keys of the map or values() method that returns a Collection view of the Map.
  • Map can be iterated either using iterator or for-each loop.
  • With Java 8 forEach statement provides a new way to loop a HashMap in Java.

That's all for this topic How to Loop Through a Map in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashMap Works Internally in Java
  2. How to Loop or Iterate an Arraylist in Java
  3. LinkedHashMap in Java With Examples
  4. How to Sort elements in different order in TreeSet using Comparator
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. Functional interfaces in Java 8
  3. Race condition in Java multi-threading
  4. Synchronization in Java - Synchronized Method And Block
  5. Difference Between Checked And Unchecked Exceptions in Java
  6. Callable and Future in Java With Examples
  7. Java Stream API Tutorial
  8. Encapsulation in Java

JavaScript Array and Object Destructuring

JavaScript destructuring assignment is a concise way to unpack values from arrays or properties from objects directly into variables. Introduced in ES6, destructuring makes code cleaner, reduces redundancy, and improves readability compared to traditional assignment methods.

Array Destructuring in JavaScript

const [India, USA, Japan] = ['Rupee', 'Dollar', 'Yen'];
console.log("Indian Currency - " + India); // Indian Currency - Rupee
console.log("American Currency - " + USA);// American Currency - Dollar
console.log("Japanese Currency - " + Japan);// Japanese Currency - Yen

Which is equivalent to this older approach of assigning array elements to variables.

const currencies = ['Rupee', 'Dollar', 'Yen'];
const India = currencies[0];
const USA = currencies[1];
const Japan = currencies[2];
console.log("Indian Currency - " + India);
console.log("American Currency - " + USA);
console.log("Japanese Currency - " + Japan);

As you can see, destructuring makes the code shorter and more expressive.

Extracting specific elements of an array

You don’t always need every element. By leaving a blank space with a comma for skipped values, you can selectively extract. For example, assigning only Rupee and Yen.

const currencies = ['Rupee', 'Dollar', 'Yen'];
const [India, , Japan] = currencies;

Using Destructuring when function returns an array

You can use destructuring to assign an array returned from a function to variables. Infact that's one of the most common uses of destructuring which you'll see in React.

For example useState() hook in React returns an array with exactly two values; current state and set function. Assignment for these two returned values can be done like this-

const [prevCount, setPrevCount] = useState(count);

Object destructuring in JavaScript

Object destructuring lets you pull properties directly into variables.

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
const {first, last, age} = obj;
console.log(first); // Ramesh
console.log(last); // Sharma
console.log(age); // 35

Which is equivalent to this older approach of assigning object properties to variables.

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
   
var f = obj.first;
var l = obj.last;
var ag = obj.age;

Assigning different names

When destructuring an object you have to use the same name for the variable as the mapped object key. If you want to use different names then you have to specify those names explicitly.

//specify new name after colon
const { first: firstName, last: lastName, age} = obj;
console.log(firstName);
console.log(lastName);
console.log(age);

Extracting specific properties of an object

You can extract specific properties of an object by giving just the needed keys. For example, if you need only first and age.

const obj = {first: 'Ramesh', last: 'Sharma', age: 35 };
const {first, age} = obj;

Passing destructured object as function arguments

If you have a function that takes object as an argument then you can pass the destructured object as function arguments to make your function more readable.

// function taking params as destructuring
function displayPerson({first, last, age}){
  console.log("first ", first, "last ", last, "age ", age)
}

That's where you will see its usage in React, to destructure props object.

In calling component-

<Person first="Ramesh" last="Sharma" age=35 />

Person Component with props

const Person = (props) => {
  return(
    <h2>{props.first} {props.last} {props.age}</h2>
  );
}

Same thing with props destructuring

const Person = ({first, last, age}) => {
  return(
    <h2>{first} {last} {age}</h2>
  );
}

Why Use JavaScript Array and Object Destructuring

  1. Cleaner syntax- Requires fewer lines of code.
  2. Improved readability- It is instantly clear which value is being extracted.
  3. Flexibility- Provides flexibility to skip values, rename properties, set default values.
  4. Modern best practice- Widely used in frameworks like React, Node.js, and Next.js.

That's all for this topic JavaScript Array and Object Destructuring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. JavaScript Spread Operator
  2. JavaScript let and const With Examples
  3. JavaScript Arrow Function With Examples
  4. React HelloWorld App - First React App
  5. React Declarative Approach

You may also like-

  1. What Are JVM, JRE And JDK in Java
  2. Java Record Class With Examples
  3. React Virtual DOM
  4. Controlled and Uncontrolled Components in React
  5. Angular Cross Component Communication Using Subject Observable
  6. Angular Property Binding With Examples
  7. First LangChain Program: Ask Me Anything
  8. Dependency Injection Using factory-method in Spring

Java DelayQueue With Examples

DelayQueue in Java is an implementation of BlockingQueue interface introduced in Java 5 as part of the java.util.concurrent package. Alongside other concurrent utilities like CyclicBarrier, Exchanger, ConcurentSkipListMap, CopyOnWriteArraySet, it provides developers with advanced concurrency tools for building scalable applications.

DelayQueue is Unbounded

The DelayQueue in Java is an unbounded implementation of BlockingQueue, that's where it is different from the other implementations of BlockingQueue like ArrayBlockingQueue (Always bounded) and LinkedBlockingQueue (both bounded and unbounded options). Though it is similar to PriorityBlockingQueue in this behaviour as PriorityBlockingQueue is also unbounded.

DelayQueue stores Delayed elements

DelayQueue in Java is a special implementation of BlockingQueue as it can only store elements of type Delayed and an element can only be retrieved from DelayQueue when its delay has expired.

Delayed interface which defines the type for the elements in the DelayQueue has one method of its own:

  1. getDelay(TimeUnit unit)- Returns the remaining delay associated with this object, in the given time unit.

Delayed interface also extends Comparable interface so compareTo(T o) method should also be implemented. This method implementation will decide whether you want to retrieve elements in ascending order of delay or descending.

According to JavaDocs "An implementation of this interface must define a compareTo method that provides an ordering consistent with its getDelay method."

So, just to sum it up; DelayQueue stores elements of type Delayed. When you implement Delayed interface two methods have to be implemented getDelay(TimeUnit unit) and compareTo(T o).

Ordering in Java DelayQueue

  1. DelayQueue orders its elements (of type Delayed) based on the remaining delay associated with the element as returned by the getDelay() method.
  2. The head of the queue is the Delayed element whose delay expired earliest.
  3. The tail of the queue is the Delayed element with the longest remaining delay.

This makes DelayQueue ideal for task scheduling, caching with expiration, and delayed message processing.

Producer Consumer Java example using DelayQueue

Let's create a producer consumer using the DelayQueue. There is also a class DelayClass which implements Delayed interface and implements the required methods- getDelay() and compareTo(). DelayQueue will store objects of DelayClass.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQDemo {
  public static void main(String[] args) {
    // delay of 2 seconds
    final long delay = 2000;
    BlockingQueue<DelayClass> delayQ = new DelayQueue<DelayClass>();
      
    // Producer thread
    new Thread(){
      @Override
      public void run() {
        for(int i = 0; i < 5; i++){
          try {
            // putting elements in delay queue
            delayQ.put(new DelayClass("item"+i, delay));
            Thread.sleep(50);
          } catch (InterruptedException e) {
            System.out.println("Error while putting values in the Queue "
             + e.getMessage());
          }
        }
      }
    }.start();
      
    // Consumer thread
    new Thread(){
      @Override
      public void run() {
        for(int i = 0; i < 5; i++){
          try {
            // retrieving elements from delay queue
            System.out.println(" Consumer got - " + delayQ.take());
            Thread.sleep(500);
          } catch (InterruptedException e) {
            System.out.println("Error while retrieving value from the Queue "
             + e.getMessage());
          }
        }
      }
    }.start();
  }
}

// Delayed interface implementing class
class DelayClass implements Delayed{
  private String item;
  private long expireTime;
  DelayClass(String item, long delay){
    this.item = item;
    // Expiretime is currenttime+delay, so if delay of 2 sec is required
    // expiration from queue will hppn after
    // currenttime + 2 sec
    this.expireTime = System.currentTimeMillis() + delay;
  }
    
  @Override
  public long getDelay(TimeUnit unit) {
    long diff = expireTime - System.currentTimeMillis();
    return unit.convert(diff, TimeUnit.MILLISECONDS);
  }
    
  @Override
  public int compareTo(Delayed o) {
    if(this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)){
      return -1;
    }
    if(this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)){
      return 1;
    }
    return 0;        
  }
    
  public String toString(){
    return "item = " + item + " expireTime = " + expireTime;
  } 
}

Output

Consumer got - item = item0 expireTime = 1458998017469
Consumer got - item = item1 expireTime = 1458998017531
Consumer got - item = item2 expireTime = 1458998017594
Consumer got - item = item3 expireTime = 1458998017656
Consumer got - item = item4 expireTime = 1458998017719

Here it can be seen elements are retrieved from the queue only after the delay expires.

đź’ĄPoints to remember

  1. DelayQueue in Java stores element of type Delayed.
  2. Element is retrieved from DelayQueue only when its delay has expired.
  3. The head of the queue is that Delayed element whose delay expired furthest in the past.
  4. If no delay has expired there is no head and poll will return null.
  5. Expiration occurs when an element's getDelay(TimeUnit tu) method returns a value less than or equal to zero.

Reference: https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/concurrent/DelayQueue.html

That's all for this topic Java DelayQueue With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java SynchronousQueue With Examples
  2. Java BlockingDeque With Examples
  3. Java LinkedTransferQueue With Examples
  4. Java ReentrantReadWriteLock With Examples
  5. Java Semaphore With Examples

You may also like-

  1. ConcurrentHashMap in Java With Examples
  2. Deadlock in Java Multi-Threading
  3. Synchronization in Java - Synchronized Method And Block
  4. Java Collections Interview Questions And Answers
  5. Java Lambda Expression And Variable Scope
  6. Autowiring in Spring Using @Autowired and @Inject Annotations
  7. Try-With-Resources in Java With Examples
  8. Java Program to Find The Longest Palindrome in a Given String

Thursday, May 7, 2026

pass Statement in Python

The pass statement in Python is a simple yet powerful tool that acts as a placeholder in your code. It performs no action when executed, but ensures that your program remains syntactically correct. This makes it especially useful when you want to define the structure of your code without implementing the logic right away.

Python pass statement

  • The pass statement is a null operation, when it is executed, nothing happens.
  • It is often used in places where a statement is required syntactically, but you don’t want to perform any operation yet.
  • Common use cases include empty functions, classes, loops, or conditional blocks that you plan to implement later.

Using pass in a Loop

If you have an array of numbers and you want to display only those numbers which are less than 100.

numbers = [89, 102, 45, 234, 67, 10, 333, 32]
for num in numbers:
  if num > 100:
    #do nothing
    pass
  else:
    print('number is', num)

Output

number is 89
number is 45
number is 67
number is 10
number is 32

In the above example, if-else statement checks whether each number in the list is greater than 100 or not. In case it is then you do nothing and that is explicitly indicated using the pass statement.

In most cases, you can write Python code without explicitly using the pass statement. However, including it often improves readability and makes your intent clear to other developers. The pass statement ensures that your code remains syntactically valid and prevents errors such as IndentationError when leaving a block empty.

Using pass in Classes

Suppose there is a Person class where you have a method to display Person data and retrieve person data. You are planning to implement retrieveData() method later, that will fetch Person details from DB, so you keep the method in place as a TODO reminder.

class Person:
    def __init__(self, name, age):
        print('init called')
        self.name = name
        self.age = age

    def display(self):
        print('in display')
        print("Name-", self.name)
        print("Age-", self.age)

    def retrieveData(self):
        #TODO has to be implemented to fetch details from DB

person = Person('John', 40)
person.display()

But running this class gives an error “IndentationError: expected an indented block

In such case adding pass statement with unimplemented method ensures that IndentationError is not thrown.

    def retrieveData(self):
        #TODO has to be implemented to fetch details from DB
        pass

So, you can see that Python pass statement can be used where you need a place holder be it with in a for loop, while loop or if-else statement, after def or even after class and in exception handling too.

pass statement with class Inheritance

If you are creating a user‑defined exception class by extending Python’s built‑in Exception class without adding new behavior, you can simply use pass statement.

class MyException(Exception):
    pass

pass Statement in Exception Handling

If you want to catch a specific exception but don't want to take any action after catching it, you can use pass statement to express that intent.

numbers = [89, 102, 0, 234, 67, 10, 333, 32]
for num in numbers:
    try:
        result = 1000/num
        print('Result is',result)
    except ZeroDivisionError:
        print('Division by Zero')
        result = 0
    except AttributeError:
        pass

That's all for this topic pass Statement in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python assert Statement
  2. Python Exception Handling Tutorial
  3. Global Keyword in Python With Examples
  4. Abstraction in Python
  5. Difference Between Function and Method in Python

You may also like-

  1. Comparing Two Strings in Python
  2. Namespace And Variable Scope in Python
  3. Passing Object of The Class as Parameter in Python
  4. Python Program to Find Factorial of a Number
  5. What Are JVM, JRE And JDK in Java
  6. Java Program to Detect And Remove Loop in a Linked List
  7. How to Read Input From Console in Java
  8. Word Count MapReduce Program in Hadoop

Java split() Method - Splitting a String

The split() method in Java String class is used to split the string into one or more substring based on the given regular expression.

Java split() method has 2 variants-

  1. split(String regex)
    • Splits this string around matches of the given regular expression.
    • Returns an array of substrings of this string that matches the given expression.
  2. split(String regex, int limit)
    • The limit parameter controls the number of times the regex pattern is applied
    • If the limit is greater than zero then the pattern will be applied at most limit - 1 times, and the resulting array will have at most limit elements.
    • The last element of the array contains the remaining part of the string.

String's split() method examples

  1. If you have a string where one (or more) spaces are used and you want to split this String around those spaces. Here passed regex "\\s+" means one or more spaces.
    public class StringSearch {
     public static void main(String[] args) {
      String str1 = "split example    program";
      String[] strArray = str1.split("\\s+");
      System.out.println("Words in array- " + strArray.length);
      for(String w : strArray){
       System.out.println("words - " + w);
      }
     }
    }
    

    Output

    Words in array- 3
    words - split
    words - example
    words – program
    
  2. If you have a date in dd/mm/yyyy format and you want to split this date String into day, month and year.
    public class StringSearch {
     public static void main(String[] args) {
      String date = "20/01/2016";
      String[] dateArr = date.split("/");
      System.out.println("" + dateArr.length);
      System.out.println("day " + dateArr[0] + " Month " + dateArr[1] +
        " Year " + dateArr[2]);
     }
    }
    

    Output

    3
    day 20 Month 01 Year 2016
    

Using split() method with limit argument

Suppose you just want the day part of the date then you can use the split() method which also passes limit as argument-

public class StringSearch {

 public static void main(String[] args) {
  String date = "20/01/2016";
  String[] dateArr = date.split("/", 2);
  System.out.println("" + dateArr.length);
  System.out.println("day " + dateArr[0]);
 }
}

Output

2
day 20

That's all for this topic Java split() Method - Splitting a String. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String Comparison in Java equals(), compareTo(), startsWith() Methods
  2. Java String substring() Method - Getting Substring
  3. String Vs StringBuffer Vs StringBuilder in Java
  4. Find All Permutations of a Given String Java Program
  5. Java String Interview Questions And Answers

You may also like-

  1. Count Number of Words in a String Java Program
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Multi-Catch Statement in Java Exception Handling
  4. final Vs finally Vs finalize in Java
  5. Java Pass by Value or Pass by Reference
  6. finalize() Method in Java
  7. Difference Between HashMap And Hashtable in Java
  8. Callable and Future in Java With Examples

Multiple Catch Blocks in Java Exception Handling

Multiple catch blocks in Java allow developers to handle different types of exceptions that may occur within a single try block. When code inside the try block throws an exception, the JVM inspects each catch clause in order. The first block whose exception type matches the thrown exception is executed, and once a matching catch block runs, the remaining ones are skipped. Execution then continues after the entire try-catch block.

This mechanism of multiple catch blocks is especially useful when a program can fail in multiple ways, for example, due to invalid array access or arithmetic errors. By defining multiple catch blocks, you can provide tailored exception handling logic for each exception type, which improves code clarity and robustness.

👉 Since Java 7, developers also have the option to catch multiple exceptions in one catch block, which eliminates the duplicated code. Refer Multi catch statement in Java to read more about it.

Multiple catch blocks Java example

In this program there is an array with only one element which is zero. From main method when calculateValue method is called a parameter is passed which is used as an index of the array.

First time 0 is passed which will mean divide by a[0]. Since the value at that index is 0 thus it will result in divide by 0 and ArithmeticException will be thrown.

Next time 2 is passed but array has only one element so trying to access a[2] will result in ArrayIndexOutOfBoundsException.

In the code there are multiple catch blocks and both of these exceptions will be caught by separate catch blocks.

public class MultipleCatchDemo {
  private void calculateValue(int i){
    int a[] = {0};
    try{
      int b = 7/a[i];
    }catch(ArithmeticException aExp){
      aExp.printStackTrace();
    }catch(ArrayIndexOutOfBoundsException aiExp){
      aiExp.printStackTrace();
    }
  }

  public static void main(String[] args) {
    MultipleCatchDemo mcDemo = new MultipleCatchDemo();
    mcDemo.calculateValue(0);
    mcDemo.calculateValue(2);
  }
}

Output

java.lang.ArithmeticException: / by zero
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:21)
java.lang.ArrayIndexOutOfBoundsException: 2
 at org.netjs.examples.impl.MultipleCatchDemo.calculateValue(MultipleCatchDemo.java:11)
 at org.netjs.examples.impl.MultipleCatchDemo.main(MultipleCatchDemo.java:22)

⛔Restrictions with Multiple catch blocks in Java

When using multiple catch blocks in Java, it is crucial to maintain the correct order of exception handling. Which means a catch block that catches a subclass of an exception must come before the catch clause that handles its exception super class.

If the superclass catch block is placed first, it will intercept all exceptions of that type, including its subclasses, making the subclass catch block unreachable. Since Java treats unreachable code as a compilation error, this ordering mistake will prevent your program from compiling.

For example, with in the Java exception handling hierarchy Exception class is super class and ArithmeticException is the child class so catch block for Exception class will catch an ArithmeticException too. Thus placing the catch block for Exception class before the catch block for ArithmeticException would mean that the catch block for ArithmeticException is never reached.

try {
    int result = 10 / 0; // ArithmeticException
} catch (Exception e) {
    System.out.println("Generic exception caught.");
} catch (ArithmeticException e) { // Unreachable Catch Block- Causes compile time error
    System.out.println("Arithmetic exception caught.");
}

In the same example as used above, if an additional catch block for Exception is placed at the beginning of the sequence, that will result in compiler error.

multiple catch blocks

That's all for this topic Multiple Catch Blocks in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Best Practices For Exception Handling in Java
  2. Creating Custom Exception Class in Java
  3. throws Keyword in Java Exception Handling
  4. Try-With-Resources in Java With Examples
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Difference Between Abstract Class And Interface in Java
  2. Inheritance in Java
  3. How to Loop Through a Map in Java
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Difference Between Thread And Process in Java
  6. Thread Priority in Java Multi-Threading
  7. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  8. Varargs (Variable-length Arguments) in Java

Wednesday, May 6, 2026

Python continue Statement With Examples

The Python continue Statement is a loop control keyword used inside for and while loops to skip the rest of the current iteration and jump directly to the next cycle of the loop. When continue is encountered, Python immediately transfers control back to the beginning of the loop, ignoring any statements that follow within that iteration.

The common use case for continue statement is to pair it with if condition with in the loop to selectively skip certain iterations. When the condition is true the continue statement is executed resulting in next iteration of the loop.

continue statement Python examples

1. Using continue statement with for loop in Python. In the example a for loop in range 1..10 is executed and it prints only odd numbers.

for i in range(1, 10):
    # Completely divisble by 2 means even number
    # in that case continue with next iteration
    if i%2 == 0:
        continue
    print(i)

print('after loop')

Output

1
3
5
7
9
after loop

2. Using continue statement with while loop in Python. In the example while loop is iterated to print numbers 1..10 except numbers 5 and 6. In that case you can have an if condition to continue to next iteration when i is greater than 4 and less than 7.

i = 0
while i < 10:
    i += 1
    if i > 4 and i < 7:
        continue
    print(i)

Output

1
2
3
4
7
8
9
10

3. Here is another example of using continue statement with infinite while loop. In the example there is an infinite while loop that is used to prompt user for an input. Condition here is that entered number should be greater than 10, if entered number is not greater than 10 then continue the loop else break out of the loop.

while True:
    num = int(input("Enter a number greater than 10: "))
    # condition to continue loop
    if num < 10:
        print("Please enter a number greater than 10...")
        continue
    else:
        break

print("Entered number is", num)

Output

Enter a number greater than 10: 5
Please enter a number greater than 10...
Enter a number greater than 10: 16
Entered number is 16

That's all for this topic Python continue Statement With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python break Statement With Examples
  2. Python return Statement With Examples
  3. pass Statement in Python
  4. Encapsulation in Python
  5. Namespace And Variable Scope in Python

You may also like-

  1. Constructor in Python - __init__() function
  2. Strings in Python With Method Examples
  3. List in Python With Examples
  4. What Are JVM, JRE And JDK in Java
  5. Equality And Relational Operators in Java
  6. Lambda Expressions in Java 8
  7. What is Hadoop Distributed File System (HDFS)
  8. Circular Dependency in Spring Framework