Friday, May 15, 2026

Named Tuple in Python

When working with tuples in Python, you can store multiple values and access them using indexes. However, if a tuple contains many fields, remembering field ordering and accessing them using index becomes quite a task and it is also less readable. This is where Named Tuple in Python shines, offering a cleaner, more descriptive way to access tuple elements.


What is a Named Tuple in Python

A named tuple is a custom tuple data type which provides ability to refer the items in the tuple by both item names as well as by index position, for example, my_tuple.field_name instead of just integer indices like my_tuple[0].

Key features are:

  1. Provides the same performance as regular tuples.
  2. Maintains immutability, values cannot be changed once created.
  3. Improves readability by allowing field name access.

Creating a named tuple

Named tuples are created using the namedtuple() factory function from the collections module.

from collections import namedtuple
#Syntax for creating named tuple
namedtuple(typename, field_names)
  • typename- The name of the new tuple subclass.
  • field_names- Represent fields which are stored in the named tuple. They can be provided as a sequence of strings like ['field1', 'field2'] or as a single space/comma‑separated string representing field names, for example 'field1 field2' or 'field1', 'field2'.

For example-

Employee = namedtuple('Employee', ['id', 'name','age'])

Here named tuple Employee is created which can store field id, name and age.

You can also provide fieldnames as a single string separated by white space.

Employee = namedtuple('Employee', 'id name age')

Python named tuple example

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', '28')
e2 = Employee('124', 'Lisa', '31')

# Access using index
print('Employee Age', e1[2])

# Access using field name
print('Employee Name', e2.name)

#iterating
for emp in [e1, e2]:
  print('Employee Id', emp.id, 'Employee Name', emp.name, 'Employee Age', emp.age)

Output

Employee Age 28
Employee Name Lisa
Employee Id 123 Employee Name Joe Employee Age 28
Employee Id 124 Employee Name Lisa Employee Age 31

Use Cases of Named Tuple in Python

1. One of the most common scenarios where Named Tuple in Python proves useful is when you need to store multiple objects of the same type. Instead of defining a full class with attributes and then creating instances, you can use a namedtuple, which is lightweight, easier to create, and still provides clear field names for readability.

Here is the example to store multiple Employees in a list using named tuples.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')
#list
employees = []
# storing named tuples
employees.append(Employee('123', 'Joe', '28'))
employees.append(Employee('124', 'Lisa', '31'))

# Access using index
print('Employee Age', employees[0][2])

# Access using field name
print('Employee Name', employees[0].name)

# iterate list
for emp in employees:
    print('Employee Id', emp.id, 'Employee Name', emp.name, 'Employee Age', emp.age)

Output

Employee Age 28
Employee Name Joe
Employee Id 123 Employee Name Joe Employee Age 28
Employee Id 124 Employee Name Lisa Employee Age 31

2. Another use case of Named Tuple in Python is when working with structured data such as CSV files. Instead of manually handling indexes or writing a full class to represent each record, you can map the CSV fields directly into a namedtuple, making the code more readable and maintainable.

import csv
from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

for emp in map(Employee._make, csv.reader(open("F:\\NETJS\\employee.csv", "r"))):
    print(emp.id, emp.name, emp.age)

Here note that _make method of the named tuple is used which is a class method that makes a new instance from an existing sequence or iterable.

Methods in named tuple

In addition to the methods inherited from tuples, named tuples support three additional methods.

1. _make(iterable)- The _make() class method creates a new namedtuple instance from an existing sequence or iterable. This is especially useful when you already have data in a list or tuple and want to convert it into a namedtuple. We have already seen an example of using _make().

2. _asdict()- Returns the namedtuple instance as a new dict (regular dict Python 3.12 onward, before that it was OrderedDict) which maps field names to their corresponding values.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', '28')
print(e1._asdict())

Output

{'id': '123', 'name': 'Joe', 'age': '28'}

3. _replace(**kwargs)- Returns a new instance of the named tuple replacing specified fields with new values.

from collections import namedtuple

# Declaring namedtuple()
Employee = namedtuple('Employee', 'id name age')

# Create custom tuple types
e1 = Employee('123', 'Joe', 28)
print(e1)
print(e1._replace(age=30))

Output

Employee(id='123', name='Joe', age=28)
Employee(id='123', name='Joe', age=30)

That's all for this topic Named Tuple 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. Concatenating Lists in Python
  2. List Comprehension in Python With Examples
  3. Class And Object in Python
  4. Passing Object of The Class as Parameter in Python
  5. Abstraction in Python

You may also like-

  1. Ternary Operator in Python
  2. Check if String Present in Another String in Python
  3. User-defined Exceptions in Python
  4. Convert String to int in Python
  5. ReentrantLock in Java Concurrency
  6. How HashMap Works Internally in Java
  7. Generics in Java
  8. Array in Java With Examples

Thursday, May 14, 2026

Tuple in Python With Examples

Tuple in Python is one of the sequence data types used to store a group of elements. Tuple is similar to Python list with one notable difference; tuple is immutable where as list is mutable.

Once a tuple is created you can’t modify its elements, since it is immutable. So performing operations like insert(),remove(), pop(), clear() are not possible on tuples.

Some of the important points about Python Tuple are-

  1. Heterogeneous Storage- A tuple can store elements of different types.
  2. Ordered- Tuple preserves the insertion order. Elements are inserted sequentially and you can iterate them in the same order.
  3. Immutable- Tuple is immutable. So, it is not possible to change content of a tuple.
  4. Indexing & Slicing- Tuples support both positive and negative indexing, as well as slicing operations.
  5. Nested & Mutable Elements- While the tuple itself is immutable, it can contain mutable objects like lists.

In this article we’ll see some of the features of the Python tuples with examples, methods in Tuple and functions that can be used with tuple.


Creating a Tuple in Python

1. In Python tuple is created by grouping elements with in parenthesis (), where the elements are separated by commas. It is the preferred way and also necessary in some scenarios.

# empty tuple
t = ()
print(t)

# tuple with items having different types
t = (12, 54, 'hello!')
print(t)

# tuple containing lists
t = ([1, 2, 3], [4, 5, 6])
print(t)

Output

()
(12, 54, 'hello!')
([1, 2, 3], [4, 5, 6])

Here note that although the tuple itself is immutable, the lists inside it can still be modified.

2. Special Case- When creating a tuple with a single element, a trailing comma is required (it is not sufficient to enclose a single value in parentheses).

t = (1)
print(type(t))

t = (1,)
print(type(t))

Output

<class 'int'>
<class 'tuple'>

As you can see, in the first assignment, type of t is integer not tuple. In the second assignment when value is followed by comma, the type of t is tuple.

3. Using the tuple() Constructor- Tuples can also be created using the built‑in tuple() constructor. An iterable can be passed as an argument to create a tuple, if no argument is passed then an empty tuple is created.

t = tuple()
print(t)
print(type(t))

Output

()
<class 'tuple'>

When argument is passed-

#Tuple as argument
t = tuple((1,2,3)) 
print(t)
print(type(t))

#List as argument
t = tuple([1, "Test", 4.56])
print(t)
print(type(t))

Output

(1, 2, 3)
<class 'tuple'>
(1, 'Test', 4.56)
<class 'tuple'>

Tuple packing and unpacking

Tuple can also be created without using parenthesis, it is known as tuple packing.

t = 3, 4, 'Hello'
print(t)
print(type(t))

Output

(3, 4, 'Hello')
<class 'tuple'>

You can also do tuple unpacking by assigning tuple items to variables, unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.

#packing
t = 3, 4, 'Hello'
print(t)
print(type(t))

#unpacking
x, y, z = t
print('x',x)
print('y',y)
print('z',z)

Output

(3, 4, 'Hello')
<class 'tuple'>
x 3
y 4
z Hello

Accessing tuple elements using index

A Tuple in Python allows element access through indexing, just like lists. The index starts at 0 for the first element and goes up to tuple_length - 1. Python also supports negative indexing, where -1 refers to the last element, -2 to the second last, and goes till tuple_length.

Here is an example showing tuple indexing for the stored elements.

To access an element of the tuple you can pass the corresponding index in the square brackets. For example to access the 5th element in a tuple you will pass tuple[4], as index starts from 0.

t = (2, 3, 6, 7, 9)
# 1st element
print(t[0])

#last element
print(t[4])

#last element
print(t[-1])

#first element
print(t[-5])

Output

2
9
9
2

Trying to pass index beyond the index range of the tuple results in ‘index error’. For example here is a tuple having 5 elements so index range for the tuple is 0..4, trying to access index 5 results in an error.

t = (2, 3, 6, 7, 9)
print(t[6])

Output

IndexError: tuple index out of range

Slicing a tuple

Just like string slicing you can do tuple slicing too which returns a new tuple.

Format of tuple slicing is as follows-

Tupleobject[start_position: end_position: increment_step]
  • start_position is the index from which the slicing starts, start_position is included.
  • end_position is the index at which the tuple slicing ends, end_position is excluded.
  • increment_step indicates the step size. For example if step is given as 2 then every alternate element from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at list_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

t = [2, 4, 6, 8, 10]
print(t[1:len(t):2]) #[4, 8]


t = [2, 4, 6, 8, 10]
print(t[::])#[2, 4, 6, 8, 10]
print(t[-3:])#[6, 8, 10]

Methods in tuple

Tuples provide the following two methods-

  • count(x)- Returns the number of items x
  • index(x)- Returns the index of the first item that is equal to x

Functions that can be used with tuple

  • len- The len() function returns the number of items of a sequence
  • min- The min() function returns the minimum element in a sequence
  • max- The max() function returns the maximum element in a sequence
  • sorted- Return a new sorted list from the items in iterable.

Operators used with tuples

Tuples can be used with the following operators which result in a creation of new tuple.

  • + (concatenation)
  • * (replication)
  • [] (slice)

Iterating a tuple

You can iterate all elements of a tuple using for or while loop.

1. Using for loop

t = [3, 1, 9, 2, 5]
for i in t:
  print(i)

Output

3
1
9
2
5

2. Using while loop

t = [3, 1, 9, 2, 5]
i = 0;
while i < len(t):
  print(t[i])
  i += 1

Output

3
1
9
2
5

del keyword with tuple

Since tuple is immutable so elements can’t be modified or removed from a tuple but tuple itself can be deleted entirely using del keyword along with tuple instance.

t = [3, 1, 9, 2, 5]

print(t)
del t
print(t)

Output

[3, 1, 9, 2, 5]
   print(t)
NameError: name 't' is not defined

Second print(t) statement results in an error as tuple t is already deleted.

That's all for this topic Tuple in Python 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. Named Tuple in Python
  2. List Comprehension in Python With Examples
  3. String Length in Python - len() Function
  4. Python Functions : Returning Multiple Values
  5. Constructor in Python - __init__() function

You may also like-

  1. Python while Loop With Examples
  2. Multiple Inheritance in Python
  3. Installing Anaconda Distribution On Windows
  4. Python Program to Display Fibonacci Series
  5. Java Multithreading Interview Questions And Answers
  6. Dependency Injection in Spring Framework
  7. String in Java Tutorial
  8. Volatile Keyword in Java With Examples

forEach Statement in Java 8

One of the most impactful features introduced in Java 8 was the combination of lambda expressions and the stream API. Alongside these came the forEach statement in Java, a concise way to iterate over collections like List and Set.

Although Map does not directly implement Iterable or Collection, it still supports forEach with a slightly different approach, making iteration across key‑value pairs seamless.

How to Use forEach() in Java

  1. Iterable interface provides forEach method as an interface default method
    default void forEach(Consumer<? super T> action)
    

    Where Consumer is a functional interface which implements the action to be performed on each iteration. If you see the default implementation of forEach in Iterable interface it is like-

    for (T t : this) {
     action.accept(t);
    }
    

    Collections like list and set implement Iterable interface so they can directly use forEach(). For example, if there is a list called numList and you want to iterate it using forEach() method it can be done like-

    numList.forEach(System.out::println);
    

    Here note that method reference is used to call println method.

TreeSet in Java With Examples

TreeSet in Java is one of the implementation of the Set interface, alongside HashSet and LinkedHashSet.

Just like other implementations of the Set interface HashSet and LinkedHashSet, TreeSet also stores unique elements. How TreeSet in Java differs from other Set implementations is that it stores its elements in sorted order. The elements are ordered using their natural ordering or a comparator can be provided at set creation time to provide custom ordering (We'll see an example a little later).

Internally, TreeSet implements the NavigableSet interface and extends AbstractSet, making it ideal for scenarios where ordering and efficient retrieval are essential.


How TreeSet is implemented in Java

TreeSet in Java uses a tree data structure to store its elements thus providing guaranteed log(n) time cost for the basic operations (add, remove and contains).

As we have seen while discussing HashSet and LinkedHashSet internally these implementations use their map counterparts i.e. HashMap and LinkedHashMap respectively. Same way TreeSet also uses TreeMap internally to store its elements.

What is Agentic AI

In this post we'll try to understand what is Agentic AI, how it works and what are the benefits of it.

The Beginning- ChatGPT and Generative AI

If we start from the beginning of the current AI boom then we can safely say that it started when ChatGPT first arrived. It opened the new avenues of interacting with Large Language Models (LLMs). For the first time, anyone could type a prompt and instantly receive:

  • Text content- Essays, stories, code snippets, explanations, summaries.
  • Images- Through integrations with generative art models.
  • Videos and multimedia- Via highly capable multimodal models that can understand, edit, and generate video content.

This was quite amazing and in a way revolutionary. It also democratized access to AI assisted creativity. Instead of needing deep technical expertise, everyday users could generate high-quality outputs with a simple conversation. Then came a shift from generation to autonomy.

From Generation to Autonomy

But the story didn’t stop at just generating content. As LLMs matured and people started using them in their day-to-day work, researchers and developers realized that these models could do more than just respond, they could act.

This gave rise to Agentic AI systems, applications where autonomous agents, powered by LLMs, can do the following:

  • Goal-driven planning- Agentic AI can independently set objectives based on user input or predefined rules, then design a step-by-step strategy to achieve them.
  • Breaking down the tasks- Goals are broken down into smaller, manageable actions. The agent evaluates multiple options and selects the most efficient path based on accuracy, speed, and expected outcomes.
  • Collaboration and integration- Agents don’t work in isolation. They interact with external systems (APIs, databases, enterprise tools) or coordinate with other agents to complete tasks seamlessly.
  • Continuous adaptation- After executing an action, the agent reviews results, gathers feedback, and adjusts its approach to improve future performance.
  • Reason and act capability- Unlike traditional AI that gives passive responses, agentic systems can reason about context and act on decisions. This means they analyze situations, choose the best course of action, and execute it through connected tools or workflows.

What Is Agentic AI

Agentic AI refers to AI systems where autonomous agents, which are often built on top of LLMs, are designed to achieve specific goals with minimal human intervention.

Key characteristics of agentic AI includes-

  • Autonomy- Agents can make decisions proactively without constant user intervention. For example, if employee onboarding in a company is done with agentic AI assistance, then instead of waiting for HR to manually trigger every step, an autonomous agent can proactively handle the process of drafting and sending a personalized welcome email, generating and sending a user ID creation request, raising a laptop request etc.
  • Tool use- They can access APIs, databases, or external systems. For example, an AI powered delivery management system, can integrate with external APIs to check real-time weather conditions and monitor traffic conditions to predict potential delays in delivery.
  • Collaboration- Agentic AI is built to work alongside humans and other AI agents. For example, in software development one agent scans the codebase and detects bugs, another agent analyzes the issue, proposes fixes, and checks with a human developer before applying changes, a third agent then runs automated tests to validate the fix.
  • Goal orientation- Instead of just answering, they aim to achieve the defined goals.

Examples of agentic AI

1. Business automation: An agent that monitors customer emails, drafts replies, and schedules meetings.

2. Software development: One agent detects bugs, another proposes fixes, and a third runs tests.

3. Research assistance: Agents that search papers, summarize findings, and generate structured reports.

4. Equity trading: Agents that can continuously monitor live stock prices and economic indicators to perform predictive analytics to forecast market movements and automatically execute trades when conditions match predefined strategies.

Generative AI Vs Agentic AI

Let’s try to see the differences between generative AI and agentic AI with the help of RAG based chatbot.

  1. Let's say you have created a customer support bot for a software company, which is a simple RAG Chatbot. Then the scenario may playout as given below.
    • User asks: "How do I reset my password?"
    • Bot retrieves relevant documentation chunks from a vector store.
    • LLM generates a grounded answer based on the provided context, it may be like this- "Go to Settings - Security - Reset Password"

    Benefit- Reduces LLM hallucination by grounding responses in provided company docs.

    Limitation- The limitation of this kind of chatbot it that it is reactive, it only answers queries, doesn’t take further action.

  2. In this case let's say there is a travel assistant bot which has access to few tools also. Then the scenario may playout as given below-
    • User asks: Book me a flight from Bangalore to Delhi tomorrow evening.
    • Bot uses LLM for natural language understanding.
    • It then calls external tools/APIs to get the task done-
      • Flight search API- To fetch available flights.
      • Payment API- To process booking payment.
      • Calendar API- Add itinerary to user's calendar.

    This chatbot comes under tool-augmented chatbot which is a step up from a simple chatbot with the benefit as-

    Benefit: Goes beyond merely generating text, it can act also by integrating with external systems.

    Limitation- It is not an agentic chatbot yet. It is task-specific, executes commands but doesn’t plan or adapt autonomously.

  3. Now we come to an agentic chatbot. Let’s say we want to automate employee onboarding end to end. Then the scenario may playout as given below-
    • HR: Employee joined today, please start onboarding process
    • Agentic bot autonomously plans onboarding workflow: welcome mail - user ID - laptop request - orientation scheduling. Then it delegates tasks to specialized agents-
      • Communication Agent- Drafts and sends personalized welcome mail.
      • IT Agent- Creates user ID and sets up access rights.
      • Asset Agent- Raises laptop request and tracks delivery.
      • HR Agent- Schedules orientation session and updates HRMS.

    Benefit: This agentic AI system is goal-driven, provides multi-step orchestration, adaptive in nature (e.g. If IT system fails, escalates to HR manager automatically).

    But it has more complex workflow with several integrations with other APIs and systems.

Drawbacks of Agentic AI

Here are some of the key drawbacks of Agentic AI, which you must keep in mind while designing an agentic AI system.

  1. Complexity in orchestration- Designing and managing multiple autonomous agents requires sophisticated workflows, monitoring, and error handling. This increases development time and maintenance overhead.
  2. Unpredictable behavior- Because agents reason and act independently, they may take unexpected actions or pursue goals in unintended ways if not carefully constrained with human oversight.
    For example, an agent tasked with maximizing profits by analyzing live stock prices and executing trades may reason that a sudden dip in a stock price is a buying opportunity and acts swiftly to buy a large volume of shares. However, it fails to account for the current news (company scandal or regulatory ban) that caused the dip.
  3. Safety and compliance risks- Autonomous execution (e.g., sending emails, making trades, or provisioning assets) can lead to compliance violations or security breaches if guardrails aren’t in place. For example a trading agent tasked with maximizing profits may engage in risky or unethical trading practices which may lead to the downfall of whole company.
  4. Coordination challenges- When agents collaborate, conflicts may arise (e.g., two agents proposing different fixes for the same bug) or even continue "debating" among themselves while ignoring human instructions. This makes arbitration and human oversight essential to keep workflows aligned and productive.
    For example, one agent detects a bug in the code. Another agent proposes a fix, while a third suggests an alternative approach. Instead of agreeing to the best approach, the agents continue exchanging arguments about which fix is better. Meanwhile, the human developer's input is sidelined, delaying resolution.
  5. Human oversight still required- Despite autonomy, most agentic systems need human validation for critical steps (e.g., financial trades, medical decisions) to avoid costly errors.

That's all for this topic What is Agentic AI. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Tools in LangChain With Examples
  2. Citation Aware RAG Application in LangChain
  3. LangChain Conversational RAG with Multi-user Sessions
  4. Embeddings in LangChain With Examples
  5. Vector Stores in LangChain With Examples

You may also like-

  1. Chain Using LangChain Expression Language With Examples
  2. Messages in LangChain
  3. Interface Default Methods in Java
  4. Convert double to String in Java
  5. Pure and Impure Pipes in Angular
  6. Abstract Class in Python
  7. Method Overloading in Python
  8. Routing in React With Example

Tuesday, May 12, 2026

Java Program - Sieve of Eratosthenes to Find Prime Numbers

In this post we'll see how to write a program in Java to find prime numbers up to a given limit using Sieve of Eratosthenes algorithm. The Sieve of Eratosthenes is one of the most efficient algorithms for finding prime numbers, especially when working with large ranges.

Sieve of Eratosthenes algorithm

Sieve of Eratosthenes algorithm work by creating a boolean array of size n+1 if the prime numbers are to be listed for range 1..n. Initially, all numbers are assumed to be prime. The algorithm then systematically eliminates non‑prime numbers by marking multiples of each prime as non-prime in the array. That's what make this algorithm efficient, for example if 2 is a prime number then none of its multiples 4, 6, 8… are going to be prime numbers. Same way if 3 is a prime number then none of its multiples 6, 9, 12, 15.. are going to be prime numbers.

After the marking is done, which ever numbers are still unmarked are prime numbers.

For example, if we have to find prime numbers in the range 1-10 then we can visualize it as given here-

Sieve of Eratosthenes

For 2, mark all the multiples of 2 as not prime-

Java Program - Sieve of Eratosthenes

For 3, mark all the multiples of 3 as not prime-

Same way for next numbers 5 and 7. At the end you will be left with the numbers that are prime. Note, that 1 is also not considered as a prime number that will be taken care of in the program by starting the loop from 2.

Sieve of Eratosthenes Java program

import java.util.Arrays;
import java.util.Scanner;

public class EratosthenesSieve {
  private static void getPrimes(int n) {
    // table to keep track of prime or not
    boolean[] primeTable = new boolean[n+1];
    // intially mark all of the array element as true
    Arrays.fill(primeTable, true);
    for(int i = 2; i <= n; i++) {
      // still true means it is a prime number
      if(primeTable[i]) {
        // multiples of i should be marked as not prime
        for(int j = i * i; j <= n; j = j+i) {
          primeTable[j] = false;
        }
      }
    }
    // print all the prime numbers which'll be the 
    // the elements in the array still marked as true
    // printing can also be done in the above for loop itself
    // after the if condition block
    for(int i = 2; i <= n; i++) {
      if(primeTable[i]) {
        System.out.print(i + " ");
      }
    }
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number for range: ");
    int n = sc.nextInt();
    getPrimes(n);
    sc.close();
  }

}

Output

Enter the number for range: 
50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 

Time and space complexity of Sieve of Eratosthenes algorithm

Outer loop runs n times.

Inner loop runs n/i times for i = 2, 3, 5…. when i = 2, the internal loop will be executed n/2 times. For i = 3, it'll be executed n/3 times. For i = 5, it'll be executed n/5 times, and so on. This results in the time complexity of O(log(log n))

Thus, the overall time complexity is O(n X log(log n))

We need an array of length n+1 for marking the non-primes so the space complexity is O(n).

That's all for this topic Java Program - Sieve of Eratosthenes to Find Prime Numbers. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Program to Check Prime Number
  2. Greatest Common Divisor (GCD) of Two Numbers Java Program
  3. Least Common Multiple (LCM) of Two Numbers - Java Program
  4. Convert float to String in Java

You may also like-

  1. Weighted Graph Adjacency Representation - Java Program
  2. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  3. Two Sum - Elements in Array With Given Sum Java Program
  4. Manacher's Algorithm to Find The Longest Palindrome - Java Program
  5. Optional Class in Java With Examples
  6. finally Block in Java Exception Handling
  7. Spring Transaction Management Example - @Transactional Annotation and JDBC
  8. Angular HttpClient - Set Response Type as Text

Resolving ClassNotFoundException in Java – Causes, Examples, and Fixes

In this article we’ll see what is java.lang.ClassNotFoundException and how to resolve ClassNotFoundException in Java.

ClassNotFoundException in Java

java.lang.ClassNotFoundException is a child class of Exception class. Being a descendant of Exception class makes it a checked exception that means it needs to be either caught in a method (with in a try-catch block), or the method needs to specify that exception in a throws clause declaration.

When is ClassNotFoundException thrown

ClassNotFoundException is thrown when the Java ClassLoader tries to load a class through its string name but the class definition cannot be found in the classpath.

Methods that can be used for loading a class through its String name are as following-

  • The Class.forName(String className) method in class Class.
  • The findSystemClass(String name) method in class ClassLoader.
  • The loadClass(String name) method in class ClassLoader.

Since class loading happens at runtime, ClassNotFoundException is always thrown during execution, not at compile time.

Java ClassNotFoundException example

As the name of the exception itself suggests this exception is thrown when the class that has to be loaded is not found. One scenario where you may find this exception is if you try to load JDBC drivers using Class.forName() but the required jar is not in the classpath.

I have also encountered ClassNotFoundException when upgrading to new version of jar in my system and using some new classes available in that jar but forgetting to update the same JAR on the test or production server. With that you get the scenario which is often quoted by the developers "In my system it is working fine"!!!

For example following program tries to load Oracle driver but the required ojdbcxx.jar is not present in the classpath.

public class JDBCCon {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("oracle.jdbc.driver.OracleDriver");

      // Creating connection
      connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
                   "root", "admin");

      // creating Statement
      Statement stmt = connection.createStatement();  

      // Executing Query
      ResultSet rs = stmt.executeQuery("Select * from Employee");

      // Processing Resultset
      while(rs.next()){
        System.out.println("id : " + rs.getInt("id") + " Name : " 
          + rs.getString("name") + " Age : " + rs.getInt("age")); 
      }
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}

Output

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
 at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
 at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
 at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
 at java.base/java.lang.Class.forName0(Native Method)
 at java.base/java.lang.Class.forName(Class.java:332)
 at org.netjs.prgrm.JDBCCon.main(JDBCCon.java:16)

As evident from the exception stack trace OracleDriver is not found so the ClassNotFoundException is thrown.

Resolving ClassNotFoundException in Java

As seen in the above example it is easy to see from the error log or exception stack trace which class is causing the exception. Then you need to check whether the required jar (where the class resides) is present in the classpath or not. So, to resolve ClassNotFoundException in Java, follow these steps-

  1. Check the Error Log- Identify the exact class name mentioned in the stack trace.
  2. Verify Classpath Configuration- Ensure the required JAR file containing the class is present in the classpath.
  3. Confirm JAR Version Compatibility- Double‑check that the class you're trying to load exists in the specific version of the JAR you're using.
  4. Package Deployment Correctly- If you’re deploying a WAR or JAR to a server, make sure all dependencies are bundled properly and there are no omissions. Missing or misplaced classes often cause this exception.
  5. Check Startup Scripts- Sometimes classpath modifications in startup scripts can override or exclude required JARs. Validate your server configuration.

That's all for this topic Resolving ClassNotFoundException in Java – Causes, Examples, and Fixes. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  2. Difference Between throw And throws in Java
  3. Multi-Catch Statement 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. intern() Method in Java String
  2. Private Methods in Java Interface
  3. Java Program to Convert a File to Byte Array
  4. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  5. ConcurrentSkipListMap in Java
  6. Spring MVC Example With @PathVariable - Creating Dynamic URL
  7. Spring Web Reactive - Spring WebFlux Example Using Annotation-Based Programming
  8. Python Installation on Windows