When it comes to counting, should a do-while loop be used, or a for loop? Because this:
class Main {
public static void main(String[] args) {
int times = 1;
do {
System.out.println("I have printed " + times + " times.");
times++;
} while (times < 6);
}
}
Seems to do the exact same thing as this:
class Main {
public static void main(String[] args) {
for (int times = 1; times < 6; times++) {
System.out.println("I have printed " + times + " times.");
}
}
}
Is it a difference in speed? Preference? Situation? Personal quirks? Some kind of "Java social taboo"? I have no idea. Either seem to be able to be used for effective counting, just that one takes a lot more. And both print the exact same thing.
System.out.println("Many thanks!!");
You're right, these do the same thing (except one starts counting at 0 and the other at 1, but that's just an implementation detail). If your program knows in advance (before the loop starts) how many times you want the loop to iterate, most Java developers will tell you to go with a for loop. That's what it's designed for.
A while loop or do while loop is better suited for situations where you're looking for a specific value or condition before you exit the loop. (Something like count >= 10 or userInput.equals("N"). Anything that evaluates to a boolean True/False value.)
When faced with these kind of dilemmas, aim for readability and familiarity. You should not concern yourself with micro-optimizations. Focus on readability and clearly conveying you intent. Do as other do in similar situation.
Like #Bill-The-Lizard said, while loop suggests to the reader of your code that you opted for it, because you're not counting, but repeating until a condition is met. At least once - otherwise you'd have chosen while(...){ } loop.
In other words, for, do {} while() and while() { } generally work the same. But one may better convey you intent in your particular piece of logic.
I think it's more of a readability and syntactic sugar. This while condition
while (condition)
can also be written as
for (; condition; )
but obviously the first one looks lot better and is more readable.
It depends on the programmer's choice when to use for loop or do while loop but the general practice followed by most of the programmers is
For loop
When you know that the loop will execute a predefined number of times(general practice since you can also use for(;true;) which loops forever).
For example a loop which runs 10 times or n number of times where n is a variable
for(int i = 0; i < n; i++) {
//Do something
}
While loop
When you know that the loop should terminate after the evaluation of a specific condition as true or else you want the loop to run forever (like while(true)) and check the break conditions inside the while loop.
Also the while loop is preferred when you can't figure out the conditions in the first place and start with while(true) but once you write code inside the loop you get good understanding of what's happening and get the idea about which conditions to check thus when to exit the loop.
For example
while(x != 0) {
//Do something;
x--;
}
while(true) {
// some code to execute on which the condition depends
if(condition is true) {
break;
}
}
Do while loop
Do while loop is similar to the while loop but with a small difference. That is it allows the first iteration to happen without checking the condition(specified in the while statement, but you can still evaluate the condition inside the block(curly braces)).
By convention most Java developers use for loops. Effective Java recommends for loops instead of while loops because the loop variable can use a tighter scope which reduces bugs. http://www.corejavaguru.com/effective-java/items/45
Recent versions of Java also allow the following
IntStream.range(0, 6).forEach(
i -> System.out.println("I have printed " + i + " times.")
);
Beyond personal preferences, this one has the advantage that the index is maintained by the runtime and there is no need for the programmer to ++i
Related
I often heard that it's bad to modify the loop counter in the body of a for loop. The following (bad) example shows what I am talking about.
for (int i=0; i<10; i++) {
i++;
}
I know that this would be allowed within while loops but could anybody explain why this is a bad practice in Java resp. even a problem in any programming language.
Two reasons why this is bad:
Readability. for( a; b; c ) { d; } is a shorthand for a; while( b ) { d; c; } explicitly for the case where you are iterating over a list. It is not strictly needed in the language. The whole point of having it is to imply intent: "I want to iterate over an entire list" or "I want to iterate over part of a list in sequence, then abort when I find something" at most.
If you add an additional increment, that will surprise other people encountering your code. If your c above says ++x or whatever, people will simply assume it loops over all items, just to then find "surprise! not always!".
OTOH, if you use a while loop, people only see the condition, and are alerted that this will be a more complex loop where the increment will not be constant.
Optimiziation. Given the above statement of intent, some optimizers will generate different code for a for statement than a while statement. Although none of them should generate wrong code, they might apply an optimization that has worse performance characteristics for non-sequential access than for sequential access.
And by "worse performance characteristics" I mean they may tell the CPU to cache the wrong code path and slow down your execution by a fraction of a cycle because data may have to be loaded into the CPU again after having needlessly been flushed.
Just look at what happens with this code:
1 for (int i=0; i<10; i++) {
2 i++;
3 }
Initially line 1 i=0.
Line 2 increments i, which now equals 1.
End of loop, so i++ takes effect, now i=2.
And so on ...
So if you really wanted to do something like this, you could have wrote it like:
for (int i=0; i<10; i+=2) {
}
Which gets the same result. It's not necessarily bad code, but it doesn't make sense to code like that, and it's very hard to troubleshoot.
Mainly because most of the programmers use it that way, so it is more readable for everyone as mentioned by #AntonH.
Side note: trying as in other language (like C if memory serves) to write:
for(int i =0; i< 10; i){
printf("%d", i);
i++;
}
This code compiles and run. In Java, the equivalent:
for(int i =0; i< 10; i){
System.out.println("%d", i);
i++;
}
Edited thanks to #David Wallace:This yields a compilation error, it is mandatory to have an assignement in the statement part of the for loop.
This question already has answers here:
Is it a bad practice to use break in a for loop? [closed]
(19 answers)
Closed 7 years ago.
I am just curious as I have been using break statements a lot, but apparently I was told that is bad practice. Obviously logically if something is met it could terminate as well. I just want to know if there is something else besides break.
That would break out of the for loop. In fact break only makes sense when talking about loops, since they break from the loop entirely, while continue only goes to the next iteration
try this:
for(int i= 0; i<MAX; i++){
if(listEmpt[i] == null){
listEmpt[i] = employeeObj;
i=MAX;
}
but I see no problem with using breaks. There will always be circumstances where you want to stop processing a loop, and using a break; makes much more sense (and makes it more readable!) than setting your loop counter up to a value that would make your loop stop at the next iteration.
you can also use labeled breaks that can break out of outer loops (and arbitrary code blocks)
looplbl: for(int i=;i<;i++){
if (i == temp)
// do something
else {
temp = i;
break looplbl;
}
}
An unlabelled break only breaks out of the enclosing switch, for, while or do-while construct. It does not take if statements into account.
See for more details.
With regards about the use of break, you could check here.
Since while loops were not covered (another form of looping which I personally use a lot), you could look towards settings conditions for the loops such as
boolean flag = true;
while (flag) {
//do something that modifies the below condition
if (condition) {
//do something
flag = false;
}
}
Upon which the loop will terminate when the condition equates to true, since that sets the flag to false.
If you simply return from within your loop, that should be sufficient. Most people think you have to terminate the loop, but this is not the case.
Also, see this answer too.
I have a code like this
public class Test
{
public static void main(String[] args)
{
continue s;
System.out.println("I am not supposed to print this");
s:
System.out.println("I am suppose to print this");
}
}
I get the error
java: undefined label: s
What is wrong ?
Basically, there is no practical way to do that in Java. You appear to be trying to do the equivalent of a "goto", and that is not supported in Java. The break label and continue label statements can only branch to an enclosing labelled statement.
Now according to the Java formal grammar you could write this:
s: {
continue s;
System.out.println("I am not supposed to print this");
}
System.out.println("I am suppose to print this");
but that still won't compile for two reasons:
The continue is only allowed to branch to a label on a loop statement. (A break doesn't have that restriction ... but ...)
The continue (or a break) makes the next statement unreachable.
See also: Alternative to a goto statement in Java
But there is one rather tricky way to get your code to "work":
static final boolean flag = true; // class attribute ...
...
s: {
if (flag) break s;
System.out.println("I am not supposed to print this");
}
System.out.println("I am suppose to print this");
The "test" there will be evaluated by the compiler so that the break is effectively unconditional. But the JLS says that the first println will be treated as reachable, so that you won't get an unreachable code error.
I guess this might be useful if you are generating this source code. Apart from that, it is (IMO) just a curiosity. It is simpler to do this with a regular if / else statement ... or by deleting the first "print" entirely.
Jumping like this is not possible in Java, only way to jump is from loops, while and do.
What is the "continue" keyword and how does it work in Java?
Read #Heinzi answer
2.2.6 No More Goto Statements
Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.
The Java Language Environment, James Gosling
and Henry McGilton, 1996
There is no "goto" in java. And "continue" does a little bit other function. You can use "continue" for example in loops like:
class ContinueDemo {
public static void main(String[] args) {
String searchMe = "peter piper picked a " + "peck of pickled peppers";
int max = searchMe.length();
int numPs = 0;
for (int i = 0; i < max; i++) {
// interested only in p's
if (searchMe.charAt(i) != 'p')
continue;
// process p's
numPs++;
}
System.out.println("Found " + numPs + " p's in the string.");
}
}
In the example above, if for example searchMe.charAt(5) != 'p' then the loop will continue from the beginning of loop from i=6, and numPs++; will not be processed.
You can read more about this here:
Branching Statements
continue is a keyword in Java used to skip iterations of a loop.
If you are trying to find an equivalent to GOTO, you should reconsidering how you are trying to solve your problem, GOTO is never a valid option, ever.
As far as I know, there is no goto in Java (there is a keyword, but it has no meaning)
Theoretically, Java have Jump statements return and break.
The return statement jumps out of a method, with or without returning values to the calling statement.
The break statement jumps out of loops.
As mentioned in the earlier answers, goto is not available in Java, and is not considered to be a good programming practice in procedural or object oriented programming. It existed back in the days of sequential programming.
Eclipse lets me write some code like this, and doesn't show any errors:
for (SomeClass c : listOfSomeClass) if (c.someBoolean) {
// actions to take if someBoolean is true
}
Will this behave as expected, or is this not valid Java?
It's valid. The if will get repeated as many times as there are elements of listOfSomeClass. But that doesn't mean that writing Java like this is a good idea. Please don't ever do this.
You could even write something like
for (SomeClass c : listOfSomeClass) if (c.someBoolean) System.out.println(c);
if you were feeling particularly perverse.
However, when you write code, it's important to write code that another programmer can easily read, understand, and modify if necessary. Once a software system is in production, you can be fairly sure that changes will be required in it at some point in the future. What you can't be sure of is exactly what those changes will be.
So a good programmer, a professional programmer, writes his/her code in a way that makes it as easy as possible to change; and that means as easy as possible to understand. Now we professional programmers get used to seeing code laid out in certain ways. Curly braces used with for and with if, whether they're actually required or not. Consistent indentation. Intuitive use of variable names, and so on. Anything slightly unusual slows us down.
I don't want to be scratching my head, trying to work out how code works. I don't want to have to THINK about which lines are part of the for loop, or the if branch. I want code that tells me what it does, the first time I cast my eyes upon it. So, if you are EVER on the same team as me - or on the same team as any programmer who vaguely resembles me - then for the love of all that is good in this world, write this loop exactly like this.
for (SomeClass element : listOfSomeClass) {
if (element.shouldBePrinted()) {
System.out.println(element);
}
}
It works fine, but the formatting it likely to be confusing. Even you are not sure of what it will do. I suggest you use the standard formatter in eclipse to produce something like
for (SomeClass c : listOfSomeClass)
if (c.someBoolean) {
// actions to take if someBoolean is true
}
This is valid Java code and this is the same as:
for (SomeClass c : listOfSomeClass) {
if (c.someBoolean) {
// actions to take if someBoolean is true
}
}
Actually Java allows you to write a one-line statement after the for loop condition. Example:
for (int i = 0; i < 10; i++)
System.out.println(i);
Note that this style is usually discouraged since it can lead to misunderstanding of what the code does.
Informally, the for construct has this grammar:
for (...) statement
Normally, statement will take the form {set of instructions each separated by;} but, of course, it's possible to omit the braces for a single statement.
Since if (...){ } is a statement, your code is valid.
But it is obscure though: at the very least adhere to an established convention and start the if on the next line with an extra level of indentation. I always use braces when writing a for loop but that's a personal choice and plenty of well-respected coders don't.
yes it can be done,the if loop
if (c.someBoolean) {
// actions to take if someBoolean is true
}
will be executed multiple times
What ever is there immediately after the for loop will be executed.
for example
for(int i=0;i<10;i++)
System.out.println("welcome");
is same as
for(int i=0;i<10;i++)
{
System.out.println("welcome");
}
So it will print welcome 10 times.
But this example
f
or(int i=0;i<10;i++)
System.out.println("welcome");
System.out.println("outside");
will print welcome 10 times and outside one time.
The above code is similar to
for(int i=0;i<10;i++)
{
System.out.println("welcome");
}
System.out.println("outside");
if you want multiple line execution in loop then you write it like this
for (SomeClass c : listOfSomeClass)
{
//multiple lines to be executed
System.out.println("print this awesome line");
}
now if you want only a sinle code line to execute accoring to the loop then you write it like this
for (SomeClass c : listOfSomeClass)
System.out.println("print this awesome line");
now this line can be any valid line of code
thus if condition is also allowed
if(awesomeCondition)
{
System.out.println("print this awesome line in side legendary if condition");
}
thus your final code is
for (SomeClass c : listOfSomeClass)
if(awesomeCondition)
{
System.out.println("print this awesome line in side legendary if condition");
}
which is equally compatible to
for (SomeClass c : listOfSomeClass)
{
if(awesomeCondition)
{
System.out.println("print this awesome line in side legendary if condition");
}// end of IF block
}// end of for loop
It is valid. If you do not use curly braces "{", then only the first command is executed. For example, if you had another command after the "if" block, it would not be a part of your "for" loop.
Example:
for (int i=0; i<3; i++)
System.out.println(i);
System.out.println("Hello");
will print:
0
1
2
Hello
and not:
0
Hello
1
Hello
2
Hello
The second output would be printed if you had the following code:
for (int i=0; i<3; i++) {
System.out.println(i);
System.out.println("Hello");
}
However, it is recommended to use the block statement.
If you look at the Java Language Specification of for you'll see (for the enhanced for):
for ( FormalParameter : Expression ) Statement
And the definition of Statement is:
Statement:
StatementWithoutTrailingSubstatement
...
IfThenStatement
...
StatementWithoutTrailingSubstatement:
Block
...
(I have left out some of the definitions)
In other words the statement in your question is equivalent to for ( FormalParameter : Expression ) Statement where Statement: IfThenStatement.
Now in general it is advisable to use a Block instead, or at least indent for better readability. Your statement is equivalent to:
for (SomeClass c : listOfSomeClass)
if (c.someBoolean) {
// actions to take if someBoolean is true
}
Or better yet:
for (SomeClass c : listOfSomeClass) {
if (c.someBoolean) {
// actions to take if someBoolean is true
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am beginner for the programming language , I am bit confused in the basic of looping concept can any one please tell me clearly when to use the concept of For loop and when to use the while loop so that it would be very grace full for me to my future programming,
Thanks in advance
Generally, you use a for loop if you know (Or the program can know at the time of the loop) how many times you want to run a piece of code, and while loops if you do not.
However, it is possible to use them interchangably, so while it may be a bit less elegant to use one than the other, it doesn't matter too much.
Ex:
for(int i = 0; i < 100; i++){
do stuff
}
is the same as
int i = 0;
while(i < 100){
do stuff
i++;
}
, but the former looks more elegant.
Similarly,
bool condition = false;
while(condition){
do stuff
}
and
for(bool condition = false; condition;){
do stuff
}
are the same, but generally, the while loop is considered more elegant here.
In almost all cases you could use either for or while loops. You are provided with two ways of looping to help reduce the complexity of your code across different use cases.
When to use for loops
For loops are best when you know how many iterations you want to loop before you begin. For example, if you knew you wanted to print the numbers 1 through 10 in order you know you want to loop 10 times.
for(int i = 1; i <= 10; i++)
{
System.out.println(i);
}
When to use while loops
While loops are best when you want to continue looping until a specific event occurs or a condition is met. For example, let's say you wanted to print random numbers between 1 and 10 until you came across the number 5. This may take one iteration or hundreds depending on your luck.
Random rand = new Random();
int value = 0;
while(value != 5)
{
value = rand.nextInt(10);
System.out.println(value);
}
Basically you should use a for loop if you know the number of iterations this loop has to do. Even if that number is a variable (like the length of a list) it is know at runtime.
A while loop is used when you don't know the number of iteration. You mostly check a condition that can evaluate to false after any number.
You also have the do-while and the for-each loops at your disposal. The do-while is used when you know that you have at least one iteration but the number is otherwise unkown. The for-each is used to iterate over arrays and collections. It can do something for each element contained.
A for loop will give you the option to perform any or all of these three things:
Instantiate a starting iteration value (int i = 0)
Define a boolean condition on which iteration may continue (i < 10)
Provide an incrementation step (i += 2)
A valid for loop can look like this:
for(; ;) {
System.out.println("This will run forever!!!");
}
A while loop only gives you the boolean condition, which is mandatory.
You typically use the for loop when:
You know the size of the elements you must iterate over
You typically use the while loop when:
You don't know the size of the elements you must iterate over
You want to busy-wait on some value or variable
For loops are used when you know how many times you need to loop. While loops are used to loop until an event occurs.
Also, note that whatever you can do with a for loop, you can do it with a while loop (just add a variable that increments in the while loop and uses it to break out of the loop when the variable reaches a certain value).
This is one of those things that folks typically pick up by experience. First thing to realise is that any for loop can be decomposed into a while loop
for ( initialise; test ; go on to next )
can be expressed as
initialise;
while(test) {
go on to next
}
I'd suggest trying for a little while to use only while loops. What you will then find is that some of your while loops start to feel a little clumsy.
initialise;
while(test) {
my really interesting code here
go on to next
}
and you find that
for ( initialise ; test; go on to next ) {
my really interesting code here
}
reads more clearly. One common example being working your way through an array.
for ( int i; i < array.length; i++ ){
something with array[i];
}