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


  public class Main {

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

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;


====== 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

commented: So true. +15

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