Friday, May 15, 2026

if else Statement in Java With Examples

To control the execution flow, Java programming language provides two primary conditional constructs: if-else and switch-case statement. In this post we'll talk about if else statement in Java in detail along with usage examples.

The if statement can be used in several different forms depending on the complexity of your logic.

  • if statement
  • if-else statement
  • if-else-if ladder
  • nested if statement

Let's go through each one of these with examples


if statement in Java

The if statement in Java is used to test a condition and execute a block of code only if the condition evaluates to true. If the condition is false, the block is skipped.

Syntax of the Java if statement is as follows-

if(condition){
  //statement(s)
}

The condition must be a boolean expression that evaluates to either true or false. If the condition evaluates to true then the block of code enclosed in curly braces is executed. If the condition evaluates to false then the if block is skipped.

If there is only a single statement inside the if block, curly braces {} are optional, though using them is considered best practice for readability.

Java if statement flow

if condition java

Java if statement examples

1- Testing a condition to check if passed number is greater than 5 or not.

public class IfDemo {
  public static void main(String[] args) {
    int i = 10;
    if(i > 5) {
      System.out.println("Value of i is greater than 5");
    }
    System.out.println("After if statement");
  }
}

Output

Value of i is greater than 5
After if statement

2- You can also use conditional operators like Conditional-AND (&&) and Conditional-OR (||) to create a condition.

public class IfDemo {
  public static void main(String[] args) {
    int i = 10;
    String test = "Hello";
    if(i > 5 && test.equals("Hello"))
      System.out.println("Inside if");
    System.out.println("After if statement");
  }
}

Output

Inside if
After if statement

Java if-else statement

The if else statement in Java allows you to define an alternate execution path when the condition evaluates to false.

Syntax of the Java if-else statement is as follows-

if(condition){
  // if block
}else{
  // else block
}

Here condition is a boolean expression that evaluates to either true or false.

  • If the condition evaluates to true then if block is executed.
  • If the condition evaluates to false then the else block is executed.

Java if-else statement flow

if else Java

Java if-else statement examples

public class IfDemo {

  public static void main(String[] args) {
    int i = 10;
    String test = "Hello";
    if(i > 20 && test.equals("Hello")) {
      System.out.println("Inside if");
    }else {
      System.out.println("Inside else");
    }
    System.out.println("After if-else statement");
  }
}

Output

Inside else
After if-else statement

In the example condition fails therefore else block is executed.

Java if-else-if ladder

The if‑else‑if ladder in Java is used when you need to evaluate multiple conditions sequentially. It allows you to chain several if and else if statements together, followed by an optional else block. Each if and else-if statement has a condition and a particular block is executed if the condition associated with that block evaluates to true. If none of the conditions evaluates to true then the else block (if present) runs.

Syntax of Java if-else-if syntax is as follows-

if(condition1){
  // statements for condition1;
}else if(condition2){
   // statements for condition2
}else if(condition3){
  // statements for condition3
}
.
.
.
else{
  // statements if none of the above conditions are true
}

Java if-else-if examples

Suppose you have requirement to add 10% to amount if amount is greater than 5000.
Add 15% if amount is more than 3000 but less than or equal to 5000.
Add 20% if amount is more than 1000 but less than or equal to 3000.
Otherwise add 25% to the amount.

public class IfDemo {
  public static void main(String[] args) {
    int amount = 5000;
    if(amount > 5000) {
      // add 10%
      amount = amount + (amount*10/100);
    }else if (amount > 3000 && amount <= 5000) {
      // add 15%
      amount = amount + (amount*15/100);
    }else if (amount > 1000 && amount <= 3000) {
      // add 20%
      amount = amount + (amount*20/100);
    }else {
      //add 25%
      amount = amount + (amount*25/100);
    }
    System.out.println("Amount is- " + amount);
  }
}

Output

Amount is- 5750

Java nested if-else statements

It is possible to have an if-else statement inside another if-else statement in Java. It is known as a nested if-else statement. It is particularly useful when you need to perform hierarchical decision‑making, where one condition depends on the outcome of another.

Syntax of Nested if‑else in Java

if (condition1) {
  if (condition2) {
      // statements executed if both condition1 and condition2 are true
  } else {
      // statements executed if condition1 is true but condition2 is false
  }
} else {
  // statements executed if condition1 is false
}

In the given program, the nested if‑else statement in Java is used to apply different bonus percentages to the amount based on multiple conditions. There is a first level check to verify if the amount is greater than 5000 or not, with in that there is a nested if-else to check for other ranges.

public class IfDemo {

  public static void main(String[] args) {
    int amount = 8000;
    if(amount > 5000) {
      if(amount > 7000 && amount <=10000) {
        amount = amount + (amount*10/100);
      }else {
        amount = amount + (amount*5/100);
      }    
    }else {
      if (amount > 3000 && amount <= 5000) {
        amount = amount + (amount*15/100);
      }else {
        amount = amount + (amount*20/100);
      }
    }
    System.out.println("Amount is- " + amount);
  }
}

Output

Amount is- 8800

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

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Java for Loop With Examples
  2. Equality And Relational Operators in Java
  3. String in Java Tutorial
  4. static Block in Java
  5. Marker Interface in Java

You may also like-

  1. finally Block in Java Exception Handling
  2. BigDecimal in Java With Examples
  3. How to Loop or Iterate an Arraylist in Java
  4. Java Collections Interview Questions And Answers
  5. Producer-Consumer Java Program Using ArrayBlockingQueue
  6. How to Convert String to Date in Java
  7. Operator Overloading in Python
  8. Data Access in Spring Framework

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