0

Hey guys, I have a little bit confused on below code and output

Main

  public class Main {

        public static void main(String[] args) {
            ClassA classA = new ClassA();
            System.out.println("====== Before =====");
            classA.checking();
            System.out.println("===== After =====");
            classA.checking();
        }
    }

Class A

public class ClassA {

    boolean b = true;

    public String checking() {
        System.out.println("B value is " + b);
        if (b = true) {
            System.out.println("B is true");
            b = false;
        } else {
            System.out.println("B is false");
        }
        return null;
    }
}

Output

====== Before =====
B value is true
B is true
===== After =====
B value is false
B is true

Why the last line of value B in After will change from false to true ?

Edited by John_165: format code nicely

4
Contributors
4
Replies
42
Views
2 Months
Discussion Span
Last Post by Buy Business
0

Thanks @rproffitt, I have the solution.

I should use == operator to compare the equality of two strings instead of =.

Edited by John_165

1

I should use == operator to compare the equality of two strings

Hopefully that's just a slip of the keyboard, but just in case...

Yes, use == to test for equality ( = is assignment).
== works exactly as you would expect for primtives (int, boolean, char etc) but not for Objects, eg Strings
== tests that two object references are exactly the same object (are both at the same address in memory).
Eg if you read a String s from the console, and the user types "yes" then
s == "yes" will be false.
To test if two Strings are equal in the ordinary everyday sense you need the equals method, eg
s.equals("yes")

Votes + Comments
So true.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.