jayseees
jayseees

Reputation: 21

using double equal operator with boolean

So, I'm facing finals next week and I went through some old tests. This one caught my attention because I can't seem to understand the code.

public class Start {
   boolean zustand = false;

    public static void main (Strings[] args){
        Start obj = new Start();

        for(int i = 0; i <= 3; i++){
            if(obj.getZustand() == true){
                System.out.println(""+i+ " true");
            }
            else{
                System.out.println(""+i+ " false");
            }
        }
    }
    public boolean getZustand(){
        zustand = (zustand == false);
        return zustand;
    }
}

I thought the output would be

0 true
1 true
2 true
3 true

but I tried them on eclipse and the output is

0 true
1 false
2 true
3 false

Can anyone please explain to me why they're not all true?

Upvotes: 0

Views: 1721

Answers (5)

Kylelem62
Kylelem62

Reputation: 567

Every time getZustand is called, the value of the Boolean in obj is flipped.

To achieve the output you want, simply return (zustand == false), or more simply, (!zustand).

Upvotes: 0

arshajii
arshajii

Reputation: 129497

zustand = (zustand == false);
  • If zustand is true, then zustand == false is false and zustand is assigned to false.

  • If zustand is false, then zustand == false is true and zustand is assigned to true.

In other words, the line zustand = (zustand == false) flips the value of zustand (which is then returned). This explains your output.

Upvotes: 1

Erlend Kristiansen
Erlend Kristiansen

Reputation: 66

The value of zustand is alternating each time you call getZustand(). This is because you are assigning zustand with first false == false, which is true, then true == false, which is false and so on...

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103447

The zustand variable is changed every time the getZustand function is called.

zustand = (zustand == false);

This line of code is the same as zustand = !zustand. And notice that zustand is a class member field, so its value is kept across function calls.

Upvotes: 4

Elliott Frisch
Elliott Frisch

Reputation: 201439

The first iteration sets the member variable zustand to true; false == false is true. The second iteration sets the variable to false; true == false is false. Then they alternate as you posted.

Upvotes: 2

Related Questions