Can you place if immediately after for in Java? - java

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
}
}

Related

Do While Loops Versus For Loops in Java for Counting

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

Why enhanced for loop does not fail when ends with semicolon?

I'm studying for a Java certification and on one of the mock exams I saw a very odd implementation of For loop. The exercise showed the following syntax :
for (Days d: Days.values());
At the beginning, I thought that it was a syntax error, since I always knew that the syntax for the "For loop" requires curly braces or, if there is only one instruction to iterate we can skip the curly braces and set our statement aligned just after the loop.
-- Since I haven't seen before a For loop ending with semicolon ";".--
Then I tried to find some documentation about it, but unfortunately I could not find any explanation why is a legal code declaration. Only references to the following syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
The odd thing is that after all of this, I tested my code and surprisingly it compiled and ran properly. Then, based on some tests that I did (playing with the code), I discovered that it seems that the ";" works like a For loop empty but with curly braces, so, any instruction after it, it is executed only one time. (As if the code where out of the loop). But I'm not sure if this is the right interpretation of the semicolon on the enhanced for loops.
Please see the complete example:
package com.TestDays;
public class TestDays {
public enum Days { MON, TUE, WED};
public static void main(String[] args) {
int x = 0;
*for (Days d: Days.values());*
Days[] d2 = Days.values();
System.out.println(d2[2]);
}
}
Does anyone knows why this syntax is allowed?
Thank you.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-18.html
A for loop is defined as:
for ( ForControl ) Statement
; is a valid statement in Java, as is a block of statements. Not something you see often with this form of loop, but you can do things like:
int i = 2;
for(; i < 100; i*=2);
// i is now the smallest power of two greater than 100
Please note that in the documentation only mention the following syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
The "documentation" quoted your question comes from a page on TutorialsPoint (as seen by me on 2016-05-22). I'm not going to link to it, but assuming they have not corrected it (yet), you should be able to find it using a Google phrase search.
This is NOT the official documentation. The only official documentation for Java is the documentation written by Oracle (and previously Sun Microsystems) employees and published by these organizations.
TutorialsPoint has no standing. In this case, they have simply gotten the Java syntax wrong.
According to the Java 8 JLS, the real Java syntax for the enhanced for loop is1
EnhancedForStatement:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression )
Statement
EnhancedForStatementNoShortIf:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression )
StatementNoShortIf
where Statement and StatementNoShortIf include the empty statement; i.e. a bare semi-colon.
1 - The grammar rules are quoted from the Java 8 grammar. The "no short ifs" variant is about disambiguating nested if statements, and is not relevant here. In the Java 7 JLS, there are two versions of the grammar in the spec, one with the variants and one without them.
The documentation that you read is not the official documentation, since the authors would have written:
The enhanced for statement has the form for (declaration : expression) statement
This is because the braces are not needed.
A single semicolon forms a so-called _ empty statement_, and that makes your code snippet syntactically valid.
There are 3 main different ways a for-loop or enhanced for-loop can be created in Java:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
for (int i = 0; i < 5; i++) System.out.println(i);
for (int i = 0; i < 5; i++);
These 3 loops are equivalent to:
For every time i is less than 5, do whatever is between {} and increment its value by one.
For every time i is less than 5, print i and increment its value by one.
For every time i is less than 5, increment its value by one.
Its not a matter of, "why doesn't it fail", its more, "what the for-loop is being told to do".
Specifically, WHY it doesn't fail, is the way the for-loop syntax is laid out. This was explained very well in Stephen C's answer:
According to the Java 8 JLS, the real Java syntax for the enhanced for loop is
EnhancedForStatement:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression )
Statement
EnhancedForStatementNoShortIf:
for ( {VariableModifier} UnannType VariableDeclaratorId : Expression )
StatementNoShortIf
As you can see, Statement refers to any valid statement, which includes the usage of ;, as ; is a valid "Statement". Because this is allowed, there is no reason why it should fail in any case.
Infact, another way to interpret for (int i = 0; i < 5; i++); would be:
"For every time i is less than 5, run statements, and increment its value by one."
Same rules can be applied to:
for (Integer i : ints) {
System.out.println(i);
}
for (Integer i : ints) System.out.println(i);
for (Integer i : ints);

How to jump in java

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.

What's the point of using labeled statements in Java? [duplicate]

This question already has answers here:
Please explain the usage of Labeled Statements
(3 answers)
Closed 7 years ago.
I'm busy studying for my certification and I stumbled upon a concept I've never even heard before - "Labeled Statements". e.g:
'label' : 'statement'
L1: while(i < 0){
L2: System.out.println(i);
}
So my question is.. why? How is this useful and when would one want to use something like this?
The only use that I'm aware of is that you can use labels in break or continue statements. So if you have nested loops, it's a way to break out of more than one level at a time:
OUTER: for (x : xList) {
for (y : yList) {
// Do something, then:
if (x > y) {
// This goes to the next iteration of x, whereas a standard
// "continue" would go to the next iteration of y
continue OUTER;
}
}
}
As the example implies, it's occasionally useful if you're iterating over two things at once in a nested fashion (e.g. searching for matches) and want to continue - or if you're doing normal iteration, but for some reason want to put a break/continue in a nested for loop.
I tend to only use them once every few years, though. There's a chicken-and-egg in that they can be hard to understand because they're a rarely-used construct, so I'll avoid using labels if the code can be clearly written in another way.
It can be used to avoid the need for a "not found" flag.
FOUND: {
for(Type t: list)
if (t.isTrue())
break FOUND;
// handle not found.
}
This is perhaps a misuse of labels, but you can use them to break without a loop.
LABEL: {
if(condition)
break LABEL;
// do something
}
It can also be used to confuse people, which is a good reason to avoid it. ;)
http://www.google.com
while(true) break http;
I used to use those as comment statements :) Jokes aside, it is like the Go to statements in basic, which allows you to jump to a line of code, ie during a deep looping structure...
Usage:
scan: {
int c;
for (firstUpper = 0 ;
firstUpper < count ;
firstUpper += Character.charCount(c)) {
c = codePointAt(firstUpper);
if (c != Character.toLowerCase(c)) {
break scan;
}
}
return this;
}
Here is an example of inordinate break that is likely to be missed out by the rest of the replies. It allows to break a loop within switch{} statement:
loop: for(;;){
int c=in.read();
switch(c){
case -1:
case '\n':
break loop;
case 'a':
processACommand();
break;
case ...
default:
break;
}
}
I think that they are required so that you can write Fortran while pretending to write Java. Without them, the aphorism Real programmers write in Fortran whatever language they are using might be invalidated.
As other answers have stated, labels are a seldom used part of the Java language.
But in your case some other things should be considered:
The labels are quite "generic" and are in fact line numbers: L1, L2, ...
The labels are not used in the code.
You are studying material for a certification.
This means, that the L1, L2 labels are simply line numbers. I assume, that the text explaining the code refers to that line numbers. In the same way some books and papers enumerate all mathematical terms just for referencing them in the text or to make citations easier.

While Loop Weirdness in Java

I noticed that java (hence probably C) has no problem with this:
while(condition1) {
//do somethin'
} while(condition2);
Is this the same as:
while(condition1 && condition2) {
//do somethin'
}
No, you have two loops.
while(condition1) {
// do something
}
while(condition2); // second loop which does nothing.
The second loop is the same as
while(condition2) { }
EDIT: My suggestion is to use the automatic formatter in your IDE regularly. Otherwise you can create formatting which suggests the code does things it doesn't.
example 1
if (condition)
statement1;
statement2;
statement3;
In this example, it appears that the first two statements are part of the if condition, but only the first is.
example 2
http://www.google.com/
statement;
Doesn't look like legal Java, but it is, not for the reasons the formatting suggests ;)
No, they are different.
The first while(condition1) will run first.
Then comes while(condition2), which has nothing after it except a single ; which means it's just some empty statement.
Remember that in control blocks like if, for, while, if you don't use the {} braces, then only the first immediate statement after it will be considered part of it.
Example:
if (condition)
System.out.println("hello"); // prints only if condition is true.
System.out.println("no"); // not bound to the 'if'. Prints regardless.
while (condition)
; // do nothing!
System.out.println("something"); // not bound to the while
Edit The empty while loop is mentioned in the Java code conventions
7.6 while Statements
A while statement should have the following form:
while (condition) {
statements;
}
An empty while statement should have the following form:
while (condition);
There is no construct is java as shown in the first form. You have probably seen
do {
} while (cond)
EDIT : You are misreading the first form. There should have been a line break after the }. This confused me as well.

Categories