How to loop using while in Java?

Zora 77 Published: 09/16/2024

How to loop using while in Java?

I'd be happy to explain how to use a while loop in Java!

In Java, a while loop is used to repeat a block of code as long as a certain condition is true. This type of loop is particularly useful when the number of iterations is not known beforehand or when you want to perform some action repeatedly based on a condition.

Here's the basic syntax for a while loop in Java:

while (condition) {

// code to be executed while the condition is true

}

Let's break it down:

The keyword while starts the loop. In parentheses, you specify the condition that must be met for the loop to execute. This condition can involve variables, methods, and even other control structures like if statements. If the condition is false or null when evaluated, the loop will exit immediately. The code within the curly braces ({}) represents the actions you want to perform repeatedly while the condition remains true.

Here's an example of a simple while loop that prints the numbers from 0 to 4:

int i = 0;

while (i <= 4) {

System.out.println(i);

i++;

}

This code will output:

0

1

2

3

4

To demonstrate a more practical usage of while loops, let's create an example where you want to repeatedly ask the user for their name until they enter "John". We'll use a while loop to achieve this:

import java.util.Scanner;

public class AskForName {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

String name;

do {

System.out.println("Please enter your name: ");

name = scanner.nextLine();

System.out.println("Hello, " + name);

} while (!name.equalsIgnoreCase("John"));

scanner.close();

}

}

When you run this program, it will keep asking for your name until you enter "John", at which point it will stop and print "Hello, John".

That's a brief overview of while loops in Java! They're incredibly useful and versatile, allowing you to repeat code blocks based on various conditions.

Do while loop in java oracle example

Here is a Java code snippet that demonstrates the usage of do-while loop and connects to an Oracle database:

import oracle.jdbc.pool.OracleDataSource;

import oracle.jdbc.*;

import java.sql.*;

public class Main {

public static void main(String[] args) {

try {

// Load Oracle JDBC driver

Class.forName("oracle.jdbc.driver.OracleDriver");

// Create a new OracleDataSource instance

OracleDataSource ods = new OracleDataSource();

// Set the URL, username and password for the database connection

ods.setURL("jdbc:oracle:thin:@localhost:1521/orcl");

ods.setUser("scott");

ods.setPassword("tiger");

// Get a Connection from the OracleDataSource instance

Connection con = ods.getConnection();

// Create a statement object to execute SQL queries

Statement stmt = con.createStatement();

// Do-while loop example: Display all employees in the ORG table

String query = "SELECT * FROM EMPLOYEES";

ResultSet result = stmt.executeQuery(query);

do {

System.out.println("Employee Name: " + result.getString(1));

System.out.println("Employee Salary: " + result.getDouble(2));

// Print each row's data in the console

// If you want to handle any exceptions, place them here.

// For example:

if (result.wasNull()) {

System.out.println("No more records.");

break;

}

} while (result.next());

// Close the result set and statement objects

result.close();

stmt.close();

// Close the connection to Oracle database

con.close();

} catch (SQLException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

System.out.println("Oracle JDBC driver not found");

}

}

}

This code demonstrates a do-while loop that fetches and prints employee records from an ORG table. It connects to the Oracle database, executes a query to retrieve data, and then iteratively prints each record.

Here's how it works:

The code starts by loading the Oracle JDBC driver using Class.forName(). Next, it creates an OracleDataSource instance and sets its URL, username, and password properties for connecting to the database. It gets a Connection object from the OracleDataSource using its getConnection() method. Then, it creates a Statement object to execute SQL queries on the connected Oracle database. The do-while loop starts by executing a query that retrieves data from the ORG table. The result set is stored in the ResultSet object named result. Inside the loop, each row of data is fetched using the next() method and then printed to the console. If there are no more records left (i.e., wasNull() returns true), the program prints a message saying "No more records." and breaks out of the loop. Finally, the code closes all database resources: the ResultSet, Statement, and Connection objects.