next


Java Online Compiler

While Loop In java

while:

'while' is a keyword in java language which is used to execute one block of statements several number of times based on the condition.
while(condition)
 {
 ...
 ...
 }
 
In the above syntax :
if the condition is true the statements of while block is execute infinity times,if the condition is false while block is terminated.
Display 1 To 10 Using While Loop
While
                                
import java.util.*;
class WhileLoop
{
public static void main(String args[])
{
int a=1;
while(a<=10)
{
System.out.println(a);
a++;
}
}
}

Factorial Number Using While Loop
                            
import java.util.*;
class Factorial
{
public static void main(String args[])
{
int i=1,fact=1,n;
Scanner s=new Scanner(System.in);
System.out.println("Enter N Value");
n=s.nextInt();
while(i<=n)
{
fact=fact*i;
i++;
}
System.out.println("Fact is :"+fact);
}

}
                                

Display Student Details(Age Must Be 20 To 30 Between).

import java.util.*;
class StudentDetails
{
public static void main(String args[])
{
String name;
int age;
float marks;
Scanner s=new Scanner(System.in);
System.out.println("Enter Your Name");
name=s.next();
System.out.println("Enter Your Age");
age=s.nextInt();

while(age<20 || age>30)
{
System.out.println("Enter Your Age Again");
age=s.nextInt();
}
System.out.println("Enter Your marks");
marks=s.nextFloat();

System.out.println("Your name is :"+name);
System.out.println("Your age is :"+age);
System.out.println("Your marks is :"+marks);
}
}