I have done thorough research on If statements in java, but I can't for the life of me understand them.
I get that you're supposed to put in a sort of true or false statement and if it meets the requirements of the if Statement then it does something. I however do not fully understand how to write them. If someone can possibly write an example and explain it that would be much appreciated.
If statements are sometimes hard to understand if they aren't explained well. In hopes to help I'll show you some examples and explain how they work.
First you need to understand that an if statement is not as simple as True or False. It works more as if the given situation in code meets the requirements you set for it between the parenthesis it will run the code inside the brackets of the if statement.
Example 1:
int x = 5;
if(x == 5)
{
System.out.println(" X is equal to 5");
}
Whats happening hear is you are initializing the int x to be 5 and then the if statements runs to see if x is equal to 5. Since it is the code inside the if statement is run and it prints out the sentence. X is equal to 5.
If the the int x was equal to anything but five in this situation the if statement would not run the code inside because it failed to meet the requirements. Similarly you can use different operators such as; does not equal(!=), greater than or less than(<, >), and greater to or equal to and less than or equal to(<=, >=).
If you want to get more complex you can go as far as to add and or or operators in(||, or &&). This allows you to set multiple requirements in one if statement.
Example 2:
int x = 5;
int y = 2;
if(x == 5 || y == 5)
{
System.out.println("I <3 if statements");
}
What is happening in this example is the if statement is checking to see if either y or x is equal to 5. Since one of them is (x) it runs the code inside the if statement printing out the sentence. I <3 if statements.
With the use of the or operate only if neither of the requirements are met will it not operate the code inside. Having both the requirements be met is fine because at least one of them are.
Also when using || you are not limited to only 2 requirements you can go on to make as many as you desire.
Example 3:
int x = 5;
int y = 2;
if(x == 5 && y == 2)
{
System.out.println("Coding is fun");
}
With the and operator, the if statement checks to see if both the requirements are met. In this example since x is equal to 5 and y is equal to 2 the code in the if statement will run printing the text. Coding is fun.
If you look to get more in depth you can also use else if and else statements. How the work is simply if the requirements of the previous if statements were not met than it will either run the code if it is an else statement or check to see if the next set of requirements are met in the else if statement.
Example 4:
int x = 5;
if(x == 1)
{
System.out.println("X is 1");
}
else if(x == 3)
{
System.out.println("X is 3");
}
else
{
System.out.println("X is unknown");
}
What is happening is that the original if statement is checking to see if x is equal to 1. Since it is not the code inside the if statement is not run and it moves on to the else if statement. The else if statement is checking to see if x is equal to 3. Once again since it is not it skips over the code inside the else if statement and moves the the else statement. With the else statement since there is no requirements it runs the code inside no matter what and finally prints out the sentence. X is unknown.
In the event that the requirements in one of the previous statements(if, or else if) is met it will run the code inside the given one and terminate there. In other words it won't run the else regardless, only if everything else fails.
I hope I was able to help with your problem. Enjoy your coding experiences! :)
I'm not sure what you mean by "thorough research on If statements", but the principle is simple.
There's always some kind of expression that might turn out to be true or false. It's written in parentheses. Then there's a bunch of statements that are usually (but not always) written between curly braces. Some naughty developers sometimes omit the braces, if there's only one statement, but it's arguably best not to do this.
The computer starts by working out whether the expression in parentheses is true or false. If it's true, the statements in the braces are run. If it's false, the statements in the braces are ignored.
For example,
if (today.equals("Friday")) {
developers.goHome("early");
managers.stay("late");
}
Here, if today.equals("Friday") turns out to be true, the two statements inside the braces are run. Otherwise, they are not.
Let's say you have a value x that you want to check if it's bigger or smaller than five for example you can do this :
int x ;
if(x>5) { // you're checking if x is bigger than 5
// If true print it's bigger...
System.out.print("It's bigger than five");
}else{ // anything else (if not bigger) print it's not bigger...
System.out.print("It's not bigger than five");
}
So if x was 6 for example output would be
It's bigger than five
Related
If x and y are int variables. Are the following two segments of Java code behaviourally equivalent for all values of x and y? Explain why, or why not.
Version 1:
if (x > 10)
{
if (y < 20)
{System.out.print("hi");
}
}
Version 2:
if (x > 10 && y < 20)
{
System.out.print("hi");
}
I think it is equivalent but I just want to make sure I'm not missing anything. I don't see how they cannot be equivalent. Thanks.
Yes, they are completely equivalent. In situations like these it comes down to picking the one you think is clearest.
Yes, they are.
The important point which might not be so obvious is that in both versions the second comparison is only evaluated if the first one results in 'true'.
Yes, they are equivalent, but the second one is shorter, and you can add a single else clause, which you cannot do in the first, because you'd have to write two independent else clauses there.
Whether one or two else clauses should be used depends on what your logic requires, so both forms may be appropriate.
I would generally recommend the second one, but if you don't need a single else clause, and the expressions are large, the first one may end up being more readable.
Yes they are equivalent also from the semantic point of view.
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 8 years ago.
Improve this question
What is the best way to end a loop in Java?
This:
boolean exit = false;
while((a < 5) && (exit = false)){
if(a == 3)
exit = true;
else
a++;
}
Or this:
while((a < 5){
if(a == 3)
break;
else
a++;
}
Some people may find that break are harder to debug (personally, I prefer using flag) but it is principally a matter of opinion.
Imagine a loop body which contains over 500 lines of code, with some break statements located everywhere, it may be harder for you to visualise all the possibilities of exiting the loop.
Another reason of why I like using a flag is that you can give a signifiant name to the ending point instead of simply break.
Note that you can also use a flag in a for loop example :
boolean flag = false;
for(int i = 0; !flag && i < 10; i++) {
// some treatment
}
It may be interesting however, to know that when dealing with loop, there is the continue keyword which allow you to not exit the loop, but skip directly to the next iteration.
What is the best way to finish a loop in Java?
If there was really a best way between both, Java would probably not allow the other ;)
I guess the most important is to use the same convention as your co-worker so the code does not differ from class to class.
break exist for a reason, right!
while(a < 5){
if(a == 3)
break;
else
a++;
}
Very simple answer, go for the break, less flags, less to debug, easier to maintain. It is simple to change from a while to for loop without any modifications in the logic. Think of a scenario where you would need to add more conditions...
My opinion is if you don't understand the usage of break and continue then you might go for the flag all the time. But there is not only one answer. Your question is what option is better for exit the loop and from your two examples the option is simple. My opinion is the break one.
Now some will use the flag, and some the break, and they give code samples for which will fit better. But this is not your question!
I can give you lots of examples, where some I would go for the flag and other for the break and some a mix of both. It depends on what my loop is about to handle.
break is to mark that if we reach this condition, we will go out of the loop emiditely. Which is very important in some loop logic.
Even though when you/co-worker add more logic, before or after that condition, still the loop will exit where it reaches the break.
Sometimes you maybe want to flag that you reached a condition but want still to go thru all the instructions the loop covers, and here does a bool help you to stop the loop but after it went thru all the logic.
If you don't use flag/break in a right way your system can act very strange, specially when adding new logic.
Remember that you also can use break and continue with a label, which is not so common but good to know.
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
The first snippet is syntactically wrong - = is the assignment operator. You were looking for the equality operator, ==:
while ((a < 5) && (exit == false)) {
Or better yet, since exit is a boolean, just evaluate it directly:
while (a < 5 && !exit) {
Other than that, you should always strive to follow the convention of the project you're working on. If it's coding styles prefers breaks - just use them. If it prohibits them, don't.
Once you throw project guideline considerations out the window, it's completely a matter of preference. Personally, I tend to prefer the break statement, especially if I have several conditions to evaluate. E.g.:
while (a < 5) {
// do stuff
if (a == 3) {
break;
}
// do more stuff
if (b >= 19) {
break;
}
// etc...
}
But ultimately, you should evaluate it on a case-to-case basis. Preferring breaks, like I do, doesn't mean you should blindly always use them. Choose whatever makes the code look better and easier to maintain.
I depends on what you mean by "best" ? With the break, you exit the loop early, so that is more efficient.
I would prefer the first, cause goto is considered harmful. And an exit is like a goto. But more important: Please always use {} when writing a if clause.
Also, when using a condition, give it a name. It is almost simpler to understand ageBelow18 instead of today.getYear() < customer.getBirthday().getYear(); (the code is not correct, I know).
Both those options you have presented aren't as good as two alternatives.
Seeing as you directly exit the loop after a simple comparison then the best option is:
while (a < 5 && a != 3) {
a++;
}
This is because you need to check both conditions before executing the body, and you don't need to do anything special when exiting the loop.
However, if you need to do need a bit of special logic when a certain condition is hit then you should use a while true loop and breaks.
while (true) {
if (a >= 5) {
break; // nothing special, just exit
} else if (a == 3) {
a *= 2; // double a before exiting loop
break;
}
a++;
}
The while (true) shows that the only way to exit the loop is with a break, so the programmer should keep an eye out for them. The breaks should also be grouped together at the top of the loop body, so they act as guards preventing the loop body from being executed if their condition is hit.
I would choose the break statement since:
Code is more clean
No need for extra code declarations
Debug the code is easier
It's common to mess with a lot of flags declared on the condition. You will not want to get a lot of nested conditions on the same line.
There is also exist the continue keyword that will let you to skip parts of the code if necessary.
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 8 years ago.
Improve this question
Sometimes you know because of the logic behind the conditions within your if, else if that your last condition check could be omitted and be written as an else instead. This way you do one less check, however it's less clear to read. What would be good coding? Would it even be more efficient because there is one less check or does the compiler optimize for these cases?
if(x<0){
//statements
}else if(x==0){
//statements
}else if(x>0){
//statements
}
Or with else
if(x<0){
//statements
}else if(x==0){
//statements
}else{
//statements
}
In Java, there is a potential problem if you include the condition on the last else if:
String whatIsX;
if (x < 0) {
// statements
whatIsX = "x is negative";
} else if (x == 0) {
// statements
whatIsX = "x is zero";
} else if (x > 0) {
// statements
whatIsX = "x is positive";
}
System.out.println(whatIsX);
This will give you an error. The reason is that the compiler thinks that it's possible whatIsX may not have been initialized, if none of the if conditions are true. We know that's impossible, since one of the if conditions must be true (assuming x can't be changed by another thread at just the wrong time!). But the language rules don't require the compiler to try to do the kind of analysis required to figure that out.
Because of this, it's best not to include the last condition. Changing the last else if (x > 0) to simply else will make the program legal.
This is a feature of Java because of its "definite assignment" rules. The code would work fine in most other languages.
In you case you have defined it is ok to leave it out as there are only 3 possibilities.
That is
x==0 or x<0 or x>0
Considered a scenario with more possibilities it cry in for a bug when the last else is open ended cause if all the if's & else if's fail it will enter the last else as it has no bounds.
It's even a bit worse than that. Some languages will not even allow an empty block. In Bash, in some cases, you can use a colon (':') for a null statement. In Python you can say 'pass'.
Let's not even consider, here, the question of mandatory bracketing for a 1-statement block.
I think clarity in code is very important, and compilers are pretty smart about optimizing conditionals.
If one could prove that an extra test is made that will always fail and it is in code that executes a billion times per second, well ... maybe then.
Otherwise, if one must leave out the else, one might put a comment to the effect that other 'elseifs' will likely be added.
In your case, comparing the last if is not ideal as if the 1st 2 if statements are not true, then the third one has to be true. So keeping just else would be fine.
the ternary operator would be my personal choice though.
(x>0) ? //statements : (x==0) ? //statements : //statements
it basically reads
if( x>0) then statements
else if(x==0) then statements
else statements
more about ternary operator or if statement here
Last approach is correct since if it's not = 0 and < 0 then it must be > 0 and no other possibilities left out.
On a side not, you can as well consider using a switch statement
int x = 3;
switch(x) {
case 1: x < 0;
//something;
break;
case 2: x == 0;
//something;
break;
case 3: x > 0;
//something;
break;
default: break;
}
I'm writing small program, and want to get access to an element in array with the loop. And I need to increment "array index" variable for next iteration.
Here is the code:
winner[turn] = subField[(int)Math.floor(i / 10.0)][i % 10].equalsIgnoreCase("O") ? false : winner[turn];
turn++;
Is it possible to make one line of code from it?
PS: I'm trying to write less lines only for myself. It's a training for brain and logic.
Well, it can be done for sure:
winner[turn] = subField[(int)Math.floor(i / 10.0)][i % 10].
equalsIgnoreCase("O") ^ winner[turn++];
Look that there is not even ternary operator there.
But not because it is shorter it is better (and certainly not clearer). So I'd recommend you do it in these many lines:
String aSubField = subField[(int)Math.floor(i / 10.0)][i % 10];
if (aSubField.equalsIgnoreCase("O"))
winner[turn] = false;
turn++;
Look, even there is no need to assign the value in case the comparison yields false.
[edit]
YAY! Just found my XOR was wrong ... that's just the problem with golf, it tooks a lot of time to figure it is wrong .... (in this case, if the cond is true but the previous value is false, it won't work).
So let me golf it other way :)
winner[turn] = !subField[i/10][i%10].equalsIgnoreCase("O") & winner[turn++];
Note the ! and the &
[edit]
Thanks to #Javier for giving me an even more compact and confuse version :) this one:
winner[turn++] &= !subField[i/10][i%10].equalsIgnoreCase("O");
Let's break it down a bit. What you have is:
winner[turn] = (some condition) ? false : (expression involving turn)
(increment turn)
Well, why not increment turn in the array access? That means it'll be incremented by the time you evaluate expressions on the right hand side, but you can easily adjust it back to its previous value as needed.
winner[turn++] = (some condition) ? false : (expression involving (turn - 1) )
I am confused about how && operator is working
if (StringUtils.isNotEmpty(cartModification.getStatusCode())
&& (cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)))
Above statement is coming as true
while
if (StringUtils.isNotEmpty(cartModification.getStatusCode())
&& cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out))
is evluaated as false.Only difference between the 2 statements are braces.
As an additional input i have checked it with debugger and
StringUtils.isNotEmpty(cartModification.getStatusCode() =true
cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)=true
I just added extra parenthesis in the second part and it was evaluated as true, Data is same as i have pointed out in question.
Since the commentbox isn't really approriate for this one:
How about trying this in a single run.
if(StringUtils.isNotEmpty(cartModification.getStatusCode())
&& cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out))
System.out.println("First try is true");
if(StringUtils.isNotEmpty(cartModification.getStatusCode())
&& (cartModification.getStatusCode().equalsIgnoreCase(UNFCommerceCartModificationStatus.Sell_Out)))
System.out.println("Second try is true");
No matter what, you should either get no or two lines (since both statements are the same).
Note it's possible that just one line is printed, this means that any call on getStatusCode() invokes a change on any value used in at least one of the conditions.