Search code examples
javaif-statementcallprivateencapsulation

Why am i only getting towards else statement?


Please check the following programs and point out the mistake. I am getting "not ok" as result no matter whatever the input is.

package timePass;
public class TimePass{
private String password;

public String getPassword() {
    return password;
}

    public void setPassword() {
        password="no";
        }
    }
package timePass2;

import java.util.Scanner;

import timePass.TimePass;

public class TimePass2{
    public static void main(String[] args) {
        TimePass obj= new TimePass();
        Scanner sc= new Scanner(System.in);
        String p= sc.nextLine();
        TimePass tp= new TimePass();

        if(p.equals(tp.getPassword())) {System.out.println("ok");}
        else {System.out.println("not ok");}

    }
}

Solution

  • Password for tp has not been set. You have to explicitly call tp.setPassword(), otherwise tp.password is null