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 ?

Thanks @rproffitt, I have the solution.

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

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")

commented: So true. +15

was looking for the same solution. Thank you for confirming it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.