While Loop In Java

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 25:- While Loop In Java

In Java, the while loop allows you to repeatedly execute a block of code as long as a specified condition is true. The loop will continue to execute until the condition becomes false. The basic syntax of the while loop is as follows:

javaCopy code

while (condition) {    // Code to be executed repeatedly as long as the condition is true }

Here's an example of using a while loop to print numbers from 1 to 5:

javaCopy code

public class WhileLoopExample {    public static void main(String[] args) {        int count = 1;        while (count <= 5) {            System.out.println("Number: " + count);            count++;        }    } }

Output:

javascriptCopy code

Number: 1 Number: 2 Number: 3 Number: 4 Number: 5

In the example above, we initialize a variable count to 1. The while loop continues to execute as long as the condition count <= 5 is true. Inside the loop, we print the value of count and then increment it using count++. The loop will stop when the value of count becomes 6 (which is not less than or equal to 5), and the loop exits.

It's important to be cautious when using while loops to avoid infinite loops. An infinite loop occurs when the condition is always true, and the loop never terminates. To prevent this, ensure that the condition will eventually become false during the execution of the loop.

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?