What's wrong with this boolean?
I thought I understood how the boolean logic worked in Java perfectly fine.... but recently when I was writing some code I noticed something wasn't working well with my boolean variable. So, wrote a quick test code to see if my idea of how booleans work was indeed correct. It wasn't....
In the below program, the idea was to have the loop break after one iteration because the boolean variable would be changed to false. It didn't work though. The JVM outputs infinite "In the loop" prints.
So what did I miss with the boolean concept? I would appreciate the help!
Code :
public class LoopTest {
public static void main(String[] args) {
boolean isRunning = true;
while(isRunning = true) {
System.out.println("In the loop");
isRunning = false;
}
}
System.out.println("Out of the loop");
}
Re: What's wrong with this boolean?
Quote:
while(isRunning = true) {
I believe this error is on the list of classic beginner errors.
= is assignment, == is the comparision operator
Re: What's wrong with this boolean?
I thought == didn't work for boolean
Re: What's wrong with this boolean?
Re: What's wrong with this boolean?
Quote:
Originally Posted by
Norm
I believe this error is on the list of classic beginner errors.
= is assignment, == is the comparision operator
I tried making the suggested changes:
Code :
public class LoopTest {
public static void main(String[] args) {
boolean isRunning = true;
while(isRunning == true) {
System.out.println("In the loop");
isRunning = false;
}
}
System.out.println("Out of the loop");
}
The compiler returned the following errors:
Code :
javac LoopTest.java
LoopTest.java:9: <identifier> expected
System.out.println("Out of the loop");
^
LoopTest.java:9: illegal start of type
System.out.println("Out of the loop");
^
2 errors
Re: What's wrong with this boolean?
Check the placement of statement flagged as in error.
Where is it? What method is it in?
Re: What's wrong with this boolean?
Quote:
Originally Posted by
Norm
Check the placement of statement flagged as in error.
Where is it? What method is it in?
Whoops... that's a major noob error. Fixed it and it works!
Just to wrap up though, I use the comparison operator when stating boolean loop, and then the assignment operator when I want it redefined in order to end the loop?
And +1 thanks for you.
Re: What's wrong with this boolean?
You use == when comparing primitives (int, long, double etc). You use equals method when comparing Objects. However you can use == to compare Objects when you want to know if two variables reference the same object.
Since booleans are primitives you can use == but it is more widely accepted to not use comparisons at all. Since booleans have a true or false value then you just use the boolean in the condition.
Code java:
boolean bool1 = true;
boolean bool2 = false;
if(bool1)
if(! bool2)
Re: What's wrong with this boolean?