2.Iterative Statement:-
This is the second part of the flow chart.
a.) while loop:-
If we don't know no. of iteration in advance then we should go for the while loop.
Syntax:-
while(b)
{
where b should be boolean type
Action
}
1. The arguments should be the boolean type . If we are trying to provide any other type then we will get compile time error.
Example:-
while(1)
{
System.out.println("Hello");
}
Compile Time Error: Incompatible Type
Found:int
Required:boolean
2.Curly braces{ } are optional and without Curly braces { } we can take one statement under
while which should not be the declarative statement.
Example:-
while(true)
System.out.println("Hello"); valid
Example:-
while(true)
int x=10; invalid
Example:-
while(true)
{
int x=10; valid
}
Example:-
while(true)
; semi colon is valid statement
Important Loop Holes in while loop
1.Unreachable Statement Part-1
example 1:-
while(true)
{
System.out.println("Hello"); invalid
} Compile Time Error: Unreachable state
System.out.println("Hello");
example 2:-
while(true)
{
System.out.println("Hello"); invalid
} Compile Time Error: Unreachable state
System.out.println("Hello");
2.Unreachable Statement Part-2
example 1:-
int a=10,b=20;
while(a<b)
{
System.out.println("Hello"); Output is :Hello
Hello
} Hello (infinite times.....)
System.out.println("Hii");
example 2:-
int a=10,b=20;
while(a>b)
{
System.out.println("Hello"); Output is :Hii
}
System.out.println("Hii");
3.Unreachable Statement Part-3
example 1:-
while(a<b)
{ invalid
System.out.println("Hello"); Compile Time Error: Unreachable state
}
System.out.println("Hii");
while(a>b)
{ invalid
System.out.println("Hello"); Compile Time Error: Unreachable state
}
System.out.println("Hii");
Note:-Every final variable will be replaced by with the value at compile time only.
example:- final int a=10;
int b=20;
System.out.println(a); after compilation System.out.println(10);
System.out.println(b); after compilation System.out.println(b);
Next:Chapter -4/Flow Control/ do-while loop
Back:Chapter -2/Flow Control/ switch ( )
Home:
No comments:
Post a Comment
Be the first to comment!
Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.
Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
Regards,
JavaByChetan
Back To Home