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

How to Convert Date to String in Java

In most of the applications it’s a very common requirement to print dates in the required formats. For that you need to convert date to a String in Java that matches the required format.

This guide explores two approaches to convert java.util.Date to string in Java:

  • Using the legacy SimpleDateFormat (pre‑Java 8)
  • Using the DateTimeFormatter class (Java 8 and beyond)

Using SimpleDateFormat for conversion

Before Java 8, a tried and tested way to convert date to string in Java was to use SimpleDateFormat which also gives you an option to provide customized patterns like "dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss".

SimpleDateFormat resides in java.text package and extends DateFormat class which is an abstract class. DateFormat class also provides predefined styles to format dates and times.

Here note that SimpleDateFormat is not thread safe so avoid using a single instance of SimpleDateFormat across multiple threads with out proper synchronization. An alternative way is to use ThreadLocal class, see an example of how ThreadLocal can be used by storing separate instance of SimpleDateFormat for each thread here.

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time.

Let’s see an example to convert date to String using the given format.

In this example there is a method getFormattedDate() where pattern is passed as an argument. Date is converted to String using the passed pattern.

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDate {

 public static void main(String[] args) {
  FormatDate fd = new FormatDate();
  
  // For date in format Wed, Jun 8, '16
  fd.getFormattedDate("EEE, MMM d, ''yy");

  // For date in format Wednesday, June 08, 2016
  fd.getFormattedDate("EEEE, MMMM dd, yyyy");

  // For date in format 05/08/2016
  fd.getFormattedDate("MM/dd/yyyy");

  // For date in format 08/05/2016
  fd.getFormattedDate("dd/MM/yyyy");
  
  // Only time like 21:52:14:096 PM
  // in 24 hr format, with mili seconds and AM/PM marker
  fd.getFormattedDate("HH:mm:ss:SSS a");

 }
 
 public void getFormattedDate(String pattern){
  Date today;
  String result;
  SimpleDateFormat formatter;
  // Creating the date format using the given pattern
  formatter = new SimpleDateFormat(pattern);
  // Getting the date instance
  today = new Date();
  // formatting the date
  result = formatter.format(today);
  System.out.println("Pattern: " + pattern + 
    " Formatted Date - " + result);
 }
}

Output

Pattern: EEE, MMM d, ''yy Formatted Date - Sun, Aug 13, '17
Pattern: EEEE, MMMM dd, yyyy Formatted Date - Sunday, August 13, 2017
Pattern: MM/dd/yyyy Formatted Date - 08/13/2017
Pattern: dd/MM/yyyy Formatted Date - 13/08/2017
Pattern: HH:mm:ss:SSS a Formatted Date - 12:50:14:097 PM

Using DateTimeFormatter class in Java 8 for conversion

With Java 8, there is another option to convert date to a string in Java. If you have an object of type LocalDate, LocalTime or LocalDateTime you can format it using the DateTimeFormatter class. All these classes are part of new Date & Time API in Java and reside in java.time package. DateTimeFormatter is thread‑safe, immutable, and locale‑aware, making it a better choice than SimpleDateFormat.

All these classes LocalDate, LocalTime or LocalDateTime have format method that takes object of DateFormatter class as argument. Using that object of DateFormatter, pattern for conversion can be provided.

You can use static methods ofLocalizedDate(FormatStyle dateStyle), ofLocalizedTime(FormatStyle dateStyle) or ofLocalizedDateTime(FormatStyle dateStyle) based on the type of object you are using to provide the pattern for formatting. Here FormatStyle is an Enumeration with the following Enum constants. Note that these methods return a locale specific date-time formatter.
  • public static final FormatStyle FULL- Full text style, with the most detail. For example, the format might be 'Tuesday, April 12, 1952 AD' or '3:30:42pm PST'.
  • public static final FormatStyle LONG- Long text style, with lots of detail. For example, the format might be 'January 12, 1952'.
  • public static final FormatStyle MEDIUM- Medium text style, with some detail. For example, the format might ' be 'Jan 12, 1952'.
  • public static final FormatStyle SHORT- Short text style, typically numeric. For example, the format might be '12.13.52' or '3:30pm'.

DateTimeFormatter Java Example

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;

public class DateToString {

 public static void main(String[] args) {
  LocalDateTime curDateTime = LocalDateTime.now();
  System.out.println("Date before formatting " + curDateTime);
  String strDate =  getFormattedDate(curDateTime);
  System.out.println("Formatted date - " + strDate); 
 }
 
 private static String getFormattedDate(LocalDateTime dt){
  DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
  //DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
  return dt.format(df1);
 }
}

Output for FULL

Date before formatting 2017-08-13T20:08:25.056
Formatted date - Sunday, 13 August, 2017

Output for LONG

Date before formatting 2017-08-13T20:08:54.921
Formatted date - 13 August, 2017

Output for MEDIUM

Date before formatting 2017-08-13T20:09:27.308
Formatted date - 13 Aug, 2017

Output for SHORT

Date before formatting 2017-08-13T20:09:53.465
Formatted date – 13/8/17

Using ofPattern() method

You can also use ofPattern() method of the DateTimeFormatter class to provide the pattern for formatting. Using this method you can provide custom format while converting date to String in Java.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


public class DateToString {

 public static void main(String[] args) {
  LocalDateTime curDateTime = LocalDateTime.now();
  System.out.println("Date before formatting " + curDateTime);
  // Passing custom pattern
  getFormattedDate(curDateTime, "dd/MM/yyyy");
  //String strDate =  getFormattedDate(curDateTime);
  //System.out.println("Formatted date - " + strDate);
  
  getFormattedDate(curDateTime, "YYYY MMM dd");
  
  getFormattedDate(curDateTime, "MMMM dd yyyy hh:mm a");
 }

 private static void getFormattedDate(LocalDateTime dt, String pattern){
  DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
  System.out.println("Formatted date " + " For Pattern " + pattern + " is "+ dt.format(df));
 }
}

Output

Date before formatting 2017-08-13T20:20:07.979
Formatted date  For Pattern dd/MM/yyyy is 13/08/2017
Formatted date  For Pattern YYYY MMM dd is 2017 Aug 13
Formatted date  For Pattern MMMM dd yyyy hh:mm a is August 13 2017 08:20 PM

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

>>>Return to Java Programs Page


Related Topics

  1. How to Convert String to Date in Java
  2. How to Convert Date And Time Between Different Time-Zones in Java
  3. Format Date in Java Using SimpleDateFormat
  4. How to Display Time in AM-PM Format in Java
  5. How to Find Last Modified Date of a File in Java

You may also like-

  1. How to Run javap Programmatically From Java Program
  2. How to Untar a File in Java
  3. Invoking Getters And Setters Using Reflection in Java
  4. Bounded Type Parameter in Java Generics
  5. Functional Interfaces in Java
  6. Difference Between CountDownLatch And CyclicBarrier in Java
  7. Difference Between equals() Method And equality Operator == in Java
  8. Interface Default Methods in Java

Agents in LangChain With Examples

In the post Tool Calling in LangChain we saw how to execute the created tools manually by parsing the tool call sent by LLM and then explicitly invoking the required function. While effective for simple workflows, this manual orchestration quickly becomes hard to follow, when tasks demand multiple steps, dynamic reasoning and adaptive decision making.

This is where agents in LangChain change the way tools are executed. Agents automate tool calling by using a Large Language Model (LLM) as a reasoning engine. Instead of manually deciding which tool to call and when, agents use a loop to iteratively reason about a task, select necessary tools and invoke them automatically, and observe outcomes until the task is complete.

Agents in LangChain: Smarter Task Automation

At their core, agents combine four essential components:

  • LLM (The Brain): Provides reasoning and decision logic.
  • Tools: External functions, APIs, or data sources that are to be called automatically by agents.
  • Memory: Maintains context across multiple turns for continuity.
  • Agent Runtime (LangGraph): A graph-based agent runtime using LangGraph is created that defines how your agent processes information.

create_agent function in LangChain

In earlier versions of LangChain, developers had to choose between multiple specialized agent constructors such as create_react_agent, create_openai_functions_agent, and others. Each of these was tailored to a specific agent type or execution style, but this fragmented the developer experience and made maintenance harder.

Over time, the LangChain team consolidated these patterns. All the older agent creation functions were deprecated, and the unified create_agent function was introduced which builds a graph based agent runtime powered by LangGraph.

  • A graph is made up of nodes (steps) and edges (connections) that defines how your agent processes information.
  • Nodes represent actions such as calling the model, executing tools, or running middleware.
  • Edges define how the agent moves between these steps.

create_agent function syntax

create_agent(
  model,  
  tools,
  system_prompt,
  middleware,
  response_format,
  ...
)

Parameters:

  1. model
    • The LLM you want the agent to use (e.g., OpenAI, Anthropic, Gemini).
    • This is the reasoning engine that interprets input, decides actions, and generates responses.
  2. tools
    • A list of external functions or APIs the agent can call (e.g., calculator, search, database query).
  3. system_prompt
    • An optional system prompt for the LLM that sets the agent's role, tone, and behavior.
    • Example: "You are a helpful assistant that uses tools when needed."
  4. middleware
    • Optional components that intercept or modify the agent's behaviour at various stages.
    • Can be used for logging, monitoring, or injecting custom logic before/after tool calls.
  5. response_format
    • Defines how the agent should structure its final output.
    • Can be a ToolStrategy, ProviderStrategy, or a Pydantic model class.

Apart from these parameters there are other optional parameters to persist the state of graph (checkpoint), persisting data (store) and many more.

How Agent Loop Works with create_agent

Agents in LangChain
  1. Agent Node Calls the Model
    • The agent starts by sending the messages list to the language model.
    • The system prompt is applied first to guide the model's behavior.
  2. Model Produces a Response
    • The model returns an AIMessage.
    • If this AIMessage contains tool_calls, it means the model wants to use a tool.
  3. Tools Node Executes the Tools
    • The agent passes the tool calls to the Tools node.
    • Each tool is executed with the provided arguments.
    • The results are wrapped as ToolMessage objects and added back to the messages list.
  4. Agent Node Calls the Model Again
    • With the updated messages list (including tool results), the agent re invokes the model.
    • This allows the model to reason over the new information.
  5. Loop Continues
    • Repeat steps 2–4
    • The process repeats until no more tool_calls are present in the response.

LangChain Example - Agent with Web Search + Math Tools

Imagine you want an agent that can handle questions requiring both real time data and calculations. For example: "What is the commission on 15 grams of gold at 5% commission rate?"

This workflow requires two tasks-

  1. Fetching the current rate of gold per gram and then calculating cost price of given quantity.
  2. Apply the commission rate to compute the commission amount on that cost price.

So, we can define two tools for these 2 tasks:

  1. Web search tool- Searches the current market rate of gold per gram.
  2. Commission Calculator Tool- takes the cost price and commission rate, then returns the commission value.

The agent orchestrates these tools in sequence; first retrieving the gold price, then performing the commission calculation, and finally returning the complete answer to the user. Important thing here is as a developer you don’t need to call any of the tools manually it will be handled by agent run-time.

Note that the code uses OpenRouter as inference provider which needs registering with the OpenRouter and getting the API key (in case you are going to use the same setup). That API key needs to be stored in .env file with the key as "OPENROUTER_API_KEY". Needs installation of langchain-openrouter and pytz packages too.

from langchain_community.tools import DuckDuckGoSearchRun
from langchain_core.tools import tool
from langchain_openrouter import ChatOpenRouter
from langchain.agents.structured_output import ToolStrategy
from datetime import datetime
import pytz
from langchain.agents import create_agent
from dotenv import load_dotenv
load_dotenv()  # Load environment variables from .env file
from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field

# Pydantic model for structured output
class GoldCommissionResult(BaseModel):
    gold_price_per_gram: float = Field(..., description="Today's 24K gold price per gram in INR (Mumbai, IST)")
    grams: int = Field(..., description="Number of grams requested")
    cost_price: float = Field(..., description="Total cost price in INR for the requested grams")
    commission_rate: float = Field(..., description="Commission rate applied (decimal, e.g., 0.05 for 5%)")
    commission_value: float = Field(..., description="Final commission value in INR")

@tool
def search_web_tool(query: str):
    '''Tool function to search the web for the given query using DuckDuckGo search results.'''
    print(f"Searching the web for: {query}")
    search_tool = DuckDuckGoSearchRun(num_results=3)
    results = search_tool.run(query)
    return results

@tool
def calculate_commission(cost_price: float, commission_rate: float) -> float:
    '''Tool function to evaluate commission on the cost price.'''
    print(f"Calculating commission for cost price: {cost_price} and commission rate: {commission_rate}")
    return cost_price * commission_rate

model = ChatOpenRouter(model="openai/gpt-oss-120b", temperature=0.1)

system_prompt = """
You are a helpful assistant working in Mumbai, India.
All tool calls, time-sensitive tasks and responses must adhere to IST.
When asked about gold price and commission:
1. Use search_web_tool to fetch today's 24K gold price in Mumbai (per gram, INR).
2. Multiply by the grams requested to get cost price.
3. Pass that cost price into calculate_commission with the given commission rate.
"""

# Create agent with tools
agent = create_agent(model,
    tools=[search_web_tool, calculate_commission],
    system_prompt=system_prompt,
    response_format=ToolStrategy(GoldCommissionResult)
)

# This function gets today's date in IST timezone, which is crucial for accurate web search results related to gold prices in India.
def get_today_date_ist():
    ist = pytz.timezone("Asia/Kolkata")
    return datetime.now(ist).strftime("%Y-%m-%d")

today = get_today_date_ist()

result = agent.invoke({"messages": [{"role": "user", "content": f"What is the commission on 15 gram of gold on {today} price for 24K in INR at 5% commission rate?"}]})

print(result)
#final answer is in structured_response field of the result, which is an instance of GoldCommissionResult
print("Answer:",result["structured_response"])

Output

Searching the web for: 24K gold price per gram Mumbai today
Calculating commission for cost price: 243225.0 and commission rate: 0.05
{'messages': [HumanMessage(content='What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission 
rate?', additional_kwargs={}, response_metadata={}, id='560afba8-0100-4d00-9bc5-2ee91ec8404a'), AIMessage(content='', 
additional_kwargs={'reasoning_content': 'We need to get today\'s 24K gold price in Mumbai per gram, but the user asks for price on 2026-05-11. That\'s a future date. We cannot fetch future price. Probably we interpret "today\'s price" as of now (IST). The user asks "on 2026-05-11 price". That date is in future, we cannot get. We could respond that we can only fetch current price. But the instruction says: When asked about gold price and commission: Use search_web_tool to fetch today\'s 24K gold price in Mumbai (per gram, INR). So we should fetch current price. Then compute for 15 grams, commission 5%.\n\nThus steps: search web for "24K gold price per gram Mumbai today". Then calculate cost = price * 15. Then calculate commission with rate 0.05.\n\nLet\'s do search.', 'reasoning_details': [{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'We need to get today\'s 24K gold price in Mumbai per gram, but the user asks for price on 2026-05-11. That\'s a future date. We cannot fetch future price. Probably we interpret "today\'s price" as of now (IST). The user asks "on 2026-05-11 price". That date is in future, we cannot get. We could respond that we can only fetch current price. But the instruction says: When asked about gold price and commission: Use search_web_tool to fetch today\'s 24K gold price in Mumbai (per gram, INR). So we should fetch current price. Then compute for 15 grams, commission 5%.\n\nThus steps: search web for "24K gold price per gram Mumbai today". Then calculate cost = price * 15. Then calculate commission with rate 0.05.\n\nLet\'s do search.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 'id': 'gen-1778481749-VEyzaZUsFowGl8YVTxNr', 'created': 1778481749, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c5-db77-7482-8235-aa43535013e1-0', 
tool_calls=[{'name': 'search_web_tool', 'args': {'query': '24K gold price per gram Mumbai today'}, 'id': 'chatcmpl-tool-038985043b0542f19f4f98bb50691877', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 362, 'output_tokens': 215, 'total_tokens': 577, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 185}}), 
ToolMessage(content="Checktoday's livegoldrate inMumbaifor 22K and24Kgoldpergram. Get real-timepriceupdates, compare daily rates, and track 10-day historicalgoldpricetrends across major Indian cities on Upstox. 24KGoldRate.Today,goldremains deeply rooted in the culture ofMumbai. From the iconicgold'taalis' (mangalsutras) exchanged during Maharashtrian weddings to the delicategold'nath' (nose rings) adorning women during festivals,goldsignifies prosperity, blessings, and the... GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K. This is equal to 625.17 (AED) and 170.22 (USD).Goldpricein India is calculated bothperounce,gram, kilogram and tola and for the most common karats. Today'sgoldpricein India stands at ?15,234pergramfor 24 karatgold(99.9% purity), ?13,964pergramfor 22 karatgold(91.6% purity), and ?11,425pergramfor 18 karatgold(75% purity).Goldhas over the years been a perfect hedge against inflation. Investors are increasingly looking... Today24K, 22K & 18K CaratGoldPricePerGramin India (INR).This tools helps you project your potentialgoldrate aspertodaysgoldrate.", name='search_web_tool', id='b9f343d2-4312-4ee1-ab03-7afb687fba02', tool_call_id='chatcmpl-tool-038985043b0542f19f4f98bb50691877'), AIMessage(content='', additional_kwargs={'reasoning_content': 'The user asks: "What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission rate?" We need today\'s price? Actually date is 2026-05-11, which is future. We cannot fetch future price. Probably they meant today\'s price (current date). We have fetched a price: 16,215 INR per gram (source says). Need to compute cost price = 15 * 16215 = 243,225 INR. 
Then commission = 5% of that = 0.05 * 243,225 = 12,161.25 INR.\n\nWe need to call calculate_commission with cost_price and commission_rate. Then output result with details. Let\'s call calculate_commission.', 'reasoning_details': [{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'The user asks: "What is the commission on 15 gram of gold on 2026-05-11 price for 24K in INR at 5% commission rate?" We need today\'s price? Actually date is 2026-05-11, which is future. We cannot fetch future price. Probably they meant today\'s price (current date). We have fetched a price: 16,215 INR per gram (source says). Need to compute cost price = 15 * 16215 = 243,225 INR. Then commission = 5% of that = 0.05 * 243,225 = 12,161.25 INR.\n\nWe need to call calculate_commission with cost_price and commission_rate. Then output result with details. Let\'s call calculate_commission.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 'id': 'gen-1778481758-mex8jK3ZFTGVBLri5Qps', 'created': 1778481758, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c6-01d5-7f82-8647-cb759f32def0-0', tool_calls=[{'name': 'calculate_commission', 'args': {'cost_price': 243225, 'commission_rate': 0.05}, 'id': 'chatcmpl-tool-b3af5980739b4d6e936aba6193b19634', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 703, 'output_tokens': 201, 'total_tokens': 904, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 148}}), 
ToolMessage(content='12161.25', name='calculate_commission', id='31475b2e-6486-40bd-98f9-681e5d1b5409', tool_call_id='chatcmpl-tool-b3af5980739b4d6e936aba6193b19634'), AIMessage(content='', additional_kwargs={'reasoning_content': 'We need to produce final answer with details: gold price per gram, cost price for 15g, commission value. The search result gave two different numbers: 16,215 INR per gram and 15,234 INR per gram. Need to pick correct today\'s 24K gold price in Mumbai. 
The snippet includes both. Which is correct? Probably the first line "GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K." 
We'll use 16,215. Multiply 16,215 * 15 = 243,225 INR cost price. Commission 5% = 12,161.25 INR.\n\nWe should also provide a 
structured result using GoldCommissionResult. Let\'s call the function to output structured result.', 'reasoning_details': 
[{'type': 'reasoning.text', 'format': 'unknown', 'index': 0, 'text': 'We need to produce final answer with details: gold price 
per gram, cost price for 15g, commission value. The search result gave two different numbers: 16,215 INR per gram and 15,234 
INR per gram. Need to pick correct today\'s 24K gold price in Mumbai. The snippet includes both. Which is correct? Probably 
the first line "GoldPriceTodayinMumbaiis 16,215 Indian Rupee (INR)/gram24K." We\'ll use 16,215. Multiply 16,215 * 15 = 243,225 
INR cost price. Commission 5% = 12,161.25 INR.\n\nWe should also provide a structured result using GoldCommissionResult. 
Let\'s call the function to output structured result.'}]}, response_metadata={'model_name': 'openai/gpt-oss-120b', 
'id': 'gen-1778481765-OxLjqE7vxagJ3S8GCBsj', 'created': 1778481765, 'object': 'chat.completion', 'finish_reason': 'tool_calls', 
'logprobs': None, 'model_provider': 'openrouter'}, id='lc_run--019e15c6-1e35-74a0-931d-09a06aa9991f-0', 
tool_calls=[{'name': 'GoldCommissionResult', 'args': {'gold_price_per_gram': 16215, 'grams': 15, 'cost_price': 243225, 
'commission_rate': 0.05, 'commission_value': 12161.25}, 'id': 'chatcmpl-tool-9242b32b242f41efa62c40fd5d0e5343', 'type': 'tool_call'}], 
invalid_tool_calls=[], usage_metadata={'input_tokens': 751, 'output_tokens': 225, 'total_tokens': 976, 
'input_token_details': {'cache_read': 0, 'cache_creation': 0}, 'output_token_details': {'reasoning': 152}}), 
ToolMessage(content='Returning structured response: gold_price_per_gram=16215.0 grams=15 cost_price=243225.0 commission_rate=0.05 commission_value=12161.25', name='GoldCommissionResult', id='1c92da8d-4ac0-4c0c-a822-365427d5df38', 
tool_call_id='chatcmpl-tool-9242b32b242f41efa62c40fd5d0e5343')], 'structured_response': GoldCommissionResult(gold_price_per_gram=16215.0, 
grams=15, cost_price=243225.0, commission_rate=0.05, commission_value=12161.25)}
Answer: gold_price_per_gram=16215.0 grams=15 cost_price=243225.0 commission_rate=0.05 commission_value=12161.25

Points to note here

  1. Two tools are defined using the @tool decorator. In search tool DuckDuckGoSearchRun tool is used for doing the web search.
  2. Pydantic model class GoldCommissionResult is defined to instruct how the agent should structure its final output.
  3. In the create_agent function tools are configured as a list and Pydantic model class is wrapped with in the ToolStrategy class. With that agent runtime knows which tools are available and how to format the final response.
  4. In the attached output, go through the ToolMessage objects to see how interaction happens between the LLM and your code.

That's all for this topic Agents in LangChain With Examples. 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. Var type in Java - Local Variable Type Inference
  4. Java DelayQueue With Examples
  5. output() Function in Angular With Examples
  6. Python while Loop With Examples
  7. Strings in Python With Method Examples
  8. Index Route in React Router

Monday, May 11, 2026

Functional Interfaces in Java

A functional interface in Java is an interface that contains exactly one abstract method. A functional interface is also known as SAM type where SAM stands for (Single Abstract Method). They form the foundation for lambda expressions and method references, introduced in Java 8, making code more concise and expressive.

An example of functional interface with in Java would be Runnable interface which has only one method run().


Java functional interface example

interface IMyInterface {
  int getValue();
}

Here, IMyInterface qualifies as a functional interface because it defines only one abstract method getValue() (note that in an interface methods are implicitly abstract).

Radix Sort Program in Java

In this post we’ll explore how to implement Radix sort program in Java. Radix Sort belongs to the family of non-comparison-based sorting algorithms, similar to Counting Sort and Bucket Sort. It can achieve O(n) time complexity under certain conditions. It is particularly effective when sorting integers with a fixed number of digits.

How does Radix sort work

Radix sort works by doing the sorting in passes moving from least significant digit (LSD) to most significant digit (MSD). In each pass, a stable sorting algorithm (commonly Counting Sort) is applied to arrange elements based on the current digit.

If the maximum number in the array has d digits, Radix Sort performs d passes. The general logic can be expressed as:

for i = 1 to d
 Use any stable sort (like counting sort)
        to sort Arr on digit d

Following image shows how Radix sort sorts an input array in each pass. Here the maximum number is 655 so number of passes is 3.

radix sort in Java

Radix Sort Java program

Java program for Radix sort works on the following logic.

  1. Find the maximum number in the input array to determine the number of digits.
  2. Iterate through each digit of the maximum number, starting from the least significant digit.
  3. Sort the array on that digit using Counting sort.
  4. Repeat until all digits are processed, resulting in a fully sorted array.
public class RadixSort {

  public static void main(String[] args) {
    int[] arr = {80, 406, 21, 655, 55, 4, 8, 91, 87, 6};
    System.out.println("Original Array- " + Arrays.toString(arr));
    radixSort(arr);
    System.out.println("Sorted array after Radix sort- " + Arrays.toString(arr));
  }
    
  private static void radixSort(int[] arr){
    int max = getMaxElement(arr);
    int position = 1;
    while(max/position > 0){
      countingSort(arr, position);
      position *= 10;
    }        
  }
        
  private static int getMaxElement(int[] arr){
    int max = arr[0];
    for(int i = 1; i < arr.length; i++){
      if (arr[i] > max){
        max = arr[i];
      }
    }
    return max;
  }
    
  private static void countingSort(int[] arr, int position){
    int n = arr.length;
    int[] output = new int[n];
    int[] count = new int[n];
      
    //count number of times each element appear
    for(int i = 0; i < arr.length; i++){
      count[(arr[i]/position)%10]++;
    }

    // each element stores (element at current index+element
    // at previous index) to get the actual position of the element
    for(int i = 1; i < n; i++){
      count[i] = count[i] + count[i-1];
    }
  
    // for correct placement of the numbers start from the end
    for(int i = n-1; i >=0; i--){
      output[count[(arr[i]/position)%10] - 1] = arr[i];
      count[(arr[i]/position)%10]--;
    }
    // Copy output array to input to the input for 
    // the next stage of counting sort
    for(int i = 0; i < output.length; i++){
      arr[i] = output[i];
    }
    System.out.println("Counting sort at this stage " + Arrays.toString(arr));
  }
}

Output

Original Array- [80, 406, 21, 655, 55, 4, 8, 91, 87, 6]
Counting sort at this stage [80, 21, 91, 4, 655, 55, 406, 6, 87, 8]
Counting sort at this stage [4, 406, 6, 8, 21, 655, 55, 80, 87, 91]
Counting sort at this stage [4, 6, 8, 21, 55, 80, 87, 91, 406, 655]
Sorted array after Radix sort- [4, 6, 8, 21, 55, 80, 87, 91, 406, 655]

Performance of Radix Sort

If you are using Counting sort for sorting in each pass of Radix sort then time complexity of Radix sort is O(d*(n+k)). Here O(n+k) is the time complexity of counting sort and d is the number of passes over number having d digits.

Auxiliary space requirement is (n+k). Count array takes k space and the output array of the same size as input array is also used while sorting. Thus the space complexity of Radix sort is O(n+k).

That's all for this topic Radix Sort Program in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Bubble Sort Program in Java
  2. Quick Sort Program in Java
  3. Heap Sort Program in Java
  4. Java Program to Create Your Own BlockingQueue
  5. Java Program to Reverse a Number

You may also like-

  1. Reading File in Java Using Files.lines And Files.newBufferedReader
  2. How to Create PDF in Java Using OpenPDF
  3. Converting String to Enum Type in Java
  4. Java Program to Get All The Tables in a DB Schema
  5. Just In Time Compiler (JIT) in Java
  6. Reflection in Java - Getting Class Information
  7. String Vs StringBuffer Vs StringBuilder in Java
  8. Replica Placement Policy in Hadoop Framework

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