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.
Related
In Java, if should have {} except when there is only one line under if.
But then, why can the following code run on my computer?
int x=1;
int y=1;
if(x<=4)
if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");
System.out.println("***");
Here is what it looks like on my IDE:
And everything runs good. Here is the result (under it loading other resources, don't care about that. I just modified some of my code to try out the code as soon as possible.)
Java will associate the else to the last candidate if.
Your code (with braces) is equal to
if(x<=4) {
if(y>=4) {
System.out.println("%%%");
} else {
System.out.println("+++");
}
}
System.out.println("***");
A candidate if is matched when there is exactly 1 statement (ending with semicolon) or block between the if and the else.
Thanks for you all and the problem solved.
The point is, if execute the next one statement or block.
Java considers the following code as a whole statement.
`if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");`
And it follows the first if.
The last print is not in the scope of consideration, it's just caused by bad indentation.
This is your code
if(x<=4)
if(y>=4)
System.out.println("%%%");
else
System.out.println("+++");
System.out.println("***");
this is what java thinks
if(Boolean) go to next line
if(Boolean) ok this is false, go to else f
The a couple weeks ago I submit a function for code review that looked like this.
Function{
If (condition)
Else If (condition)
Else if (condition)
Else
return value
}
My lead giving the code review said "I hate else if," but he didn't say why or what I should have done instead. He just gave me the go ahead to upload this function.
My question is what are some alternatives to a bunch of "else ifs" that would make the code look more elegant and maybe perform better?
I tried pulling up his code to get an idea of what he would have done and I noticed several times he did
If (condition)
If (condition)
If (condition)
Should I avoid writing "else"? I was going to ask him but he no longer works here.
Thank you
I try to avoid "else", "else if" and also "if" and "for". In my point of view, branching and looping add complexity to code. But it's everytime depends on what you want to do. Some examples:
If you do thing like:
if fruit.isBanana() then fruit.eatBanana()
else if fruit.isOrange() then fruit.eatOrange()
...
Instead of this, you can use inheritance:
class Banana extends Fruit {
function eat() {
... yum yum yum banana ...
}
}
class Orange extends Fruit {
function eat() {
... yum yum yum orange ...
}
}
And then, if you have an instance:
fruit.eat()
Another example: If you use "if" and "for" for filtering:
longFruits = []
for fruit in fruits {
if fruit.isBanana() then longFruits.add(fruit)
}
then you can work with collections instead:
longFruits = CollectionUtils.select(fruits, Precicate.isBanana)
This is just a couple examples and technics.
You can use switches.
switch (variable) {
case 1:
doSomething();
break;
case 2:
doSomething();
break;
case 3:
doSomething();
break;
default:
doSomething();
break;
}
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Oops, I misread your question, so you probably already know this, but anyway:
This is how it works:
Example 1
if your program looks like this:
if(condition1){ doThing1(); }
else if(condition2){ doThing2(); }
else if(condition3){ doThing3(); }
else{ doThing4() }
done();
Your program is first going to check if condition1 is true. if it is, it's going to run the method doThing1(). Afterwards it will not check condition2 or condition3, and will go directly to the done()-method.
If condition1 is false, the program will check if condition2 is true. If it is, it will run the method doThing2() and afterwards it will go directly to the done()-method.
If condition1 and condition2 is false, the program will check if condition3 is true and if it is, run the doThing3()-method.
If none of the conditions are true, it will run the method doThing4() and afterwards the done-method.
Example 2:
However, if your program looks like this:
if(condition1){ doThing1(); }
if(condition2){ doThing2(); }
if(condition3){ doThing3(); }
done();
Your program first checks if condition1 is true, if it is, it runs the method doThing1()
Then it checks if condition2 is true, if it is, it runs the doThing2()-method
Then it checks if condition3 is true, if it is, it runs the doThing3()-method
Lastly, it runs the done()-method.
The difference is that in example 1, the program doesn't check condition2 or condition3 if condition1 is true, whereas in example 2, it always checks all of the conditions. This means that in example 1, only one of the methods doThing1(), doThing2(), doThing3() and doThing4() is going to be run. In example 2 however, if more than one of the conditions are true, the program will run more than one of the methods.
Try writing a simple program where you use the two examples and change doThing1(); to System.out.println("1"); and so on, and try out different combinations of values (true or false) for the conditions if you didn't understand my answer.
I would use spacing to make sure the code looks neat without changing the actual meaning of the code. you can use switch, as explained in shinjw:s answer, but that isn't always practical since you have to use a byte, short, char or int to determine the outcome. Just write
if(condition1) //place1
else if(condition2) //place2
else if(condition3) //place3
else //place4
to make sure the conditions are nicely lined up if you want that, but only use that if the thing you are going to write at place 1,2,3 and 4 is one line. Otherwise it looks weird. If lining up the conditions isn't that important, I would write
if(condition1) //code1
else if(condition2) //code2
else if(condition3) //code3
else //code4
Since Java isn't space sensitive, any place you could use one space you could use any number of spaces and anytime you could use one new line, you could use any number of blank lines. It's not the tabbing, but the {} that divides code.
Right up front: I like else if. I think it makes for good clean code, unless one can design away the need for a series of comparisons. That said, ...
else if is not a first-class construct in Java. It's actually an if nested inside an else. From the JLS 7 (since OP indicates they use Java 6 and I don't have the JLS for that), an IfThenElseStatement is
if ( Expression ) StatementNoShortIf else Statement
where Expression is any Java Expression that evaluates to a boolean or Boolean, and StatementNoShortIf is any Java Statement that does not end in an if with no else.
We get an else if by substituting another if statement for Statement (following the else). So
// example 1
if (condition0) {
// body 0
} else if (condition1) {
// body 1
} else if (condition2) {
// body 2
} else {
// body 3
}
is, as far as Java is concerned, identical to:
// example 2
if (condition0) {
// body 0
} else {
if (condition1) {
// body 1
} else {
if (condition2) {
// body 2
} else {
// body 3
}
}
}
The only difference syntactically is that in example 2 no braces have been omitted (or, put another way, nested if statements have been enclosed in a Block). The else if construct is possible solely because those enclosing Blocks are unnecessary.
It is possible that your former lead prefers to use braces wherever they can be used, thinking that this is somehow safer or more readable. I disagree with this idea: as I said, else if makes for cleaner code IMO. But the only time a series of disconnected if statements better in any sense than if else is when the conditions and associated actions are truly independent of each other.
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
}
}
I'm having trouble with these if statements and can't figure out the problem:
If I try changing them to a nested if, else if format I get a compiler error saying "else" with no if statement.
The if statements don't even work, as you can see from the ouput below they all run even when the strings aren't equal.
Any help would be great. Thanks!
if (labelArray[0] == e.getSource() && myAppliance.size() >= 1) {
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("CLOCK")); {
System.out.println(options[0]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("LAMP")); //"Clock", "Lamp", "Television"
{
System.out.println(options[1]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
if (myAppliance.get(0).getClass().getName().toUpperCase().equals("TELEVISION")); {
System.out.println(options[2]);
System.out.println(myAppliance.get(0).getClass().getName());
infoBox((myAppliance.get(0).toString()),"Info");
}
}
Output:
Clock
Clock
Lamp
Clock
Television
Clock
Remove the ; at the end of the lines with the ifs.
remove the ; from immediate after if statements, compilers take them as statements and it defeats the purpose of using if itself.
Ifs work on the next statement they can take, so they'll run on the next line or treat a block enclosed on curly braces as a statement. By writing ; after the if, it's basically using an empty statement, then just proceeding to execute your block of code regardless.
Just remove the ; and it should work.
I had an if statement checking some value, And encountered a weird bug(Not sure!). My code was incorrect syntactically and in result it produced a wrong result, however eclipse didn't raised any error while compiling. Why My below code worked?
if((this.trackPointList.get(point).getTurnOutId().equals(seg.getSegRef().getTurnOut())) && seg.getSegRef().getKind().equals("arc")); // <---- See here I have semicolon
{
... code to run ...
}
Above code check only first condition and ignores seg.getSegRef().getKind().equals("arc") but I guess this should raised an issue at compile time, Am I right? My logic worked once I debugged it by skimming line by line and found this semicolon. I will appreciate if someone could explain, if it is a valid syntax.
Enlighten Me, Please!
The ; makes Java think that the body of the if conditional is complete, even if there is no other code preceding it. In effect, the code in the if statement is executed, but no body exists because the ; is there.
The { ...code to run...} is just a code block that executes, and anything declared inside that block is not visible outside the block. It will always run here because it's not part of the if block.
edit: here's another stack overflow question about the { } blocks: What do curly braces in Java mean by themselves?
The code is syntactically correct. You can write ifs without braces, like:
if(condition) statement;
Having empty statements is also valid. For instance this code is valid:
int a = 0;;
;;;
So an empty if is valid as well, although it doesn't make much sense :)
if(condition);
An if statement followed by a semicolon is called an "empty if statement".
It rarely is of any use, but it's syntactically legal.
You can write something like this
if ( doSomethingThatReturnsABoolean() )
; // Empty statement
else
doSomeOtherThing()
but it would be better to write
if ( !doSomethingThatReturnsABoolean() )
doSomeOtherThing()
Regarding your observation that only the first condition gets checked:
If the first condition returns false the second condition will not get checked, because
(false && secondCondition)
always equals to false, so the value of secondCondition is irrelevant.
The ; after the if(..) statement represents an empty statement that is executed conditionally when the if(..) evaluates to true. The { .. } represents a code block that always executes with it's own scope.
The second condition may be ignored if the first condition is false due to short-circuit evaluation.
if(condition); is equivalent to if(condition){}
same thing with for loop & while loop:
for(;condition;); is equivalent to for(;condition;){}
while(condition); is equivalent to while(condition){}