What will be the result of compilation and execution of the following code:
 
class User {
    private int id = 0;
    private String name;
    private String surname;
    
    public User () {}
    
    public User (int id, String name, String surname) {
        this.id = id;
        this.name = name;
        this.surname = surname;
    }

    Override
    public boolean equals (Object obj) {
        
        if (this == obj)
            return true;
        
        if (obj == null ||! getClass (). equals (obj.getClass ()))
            return false;
        
        User u = (User) obj;
        
        return id == u.id
            & Amp; & amp; name == u.name || (name! = null & amp; & amp; name.equals (u.name))
            & Amp; & amp; surname == u.surname || (surname! = null & amp; & amp; surname.equals (u.surname));
        
    }
    
    Override
    public int hashCode () {
        
        return id +
            name == null? 0: name.hashCode () +
            surname == null? 0: surname.hashCode ();
    }
    
    public static void main (String args []) {

        User u1 = new User (12, "name", null);
        User u2 = new User (12, null, "name");
        
        System.out.println (u1.hashCode () == u2.hashCode ());
        System.out.println (u1.equals (u2));
    }
}
 
    
Explanation
Actual execution of the method hashCode will be like this:
 
return ((id + name) == null? 0: name.hashCode() + surname) == null? 0: surname.hashCode();
 
Because of this null-field-type String concatenated with numbers and tested for null. If you write:
 
return id +
     (name == null? 0: name.hashCode ()) +
     (surname == null? 0: surname.hashCode ());
 
the execution will take place normally and the result will be: 
true
false

and also with annotation @Override, it comes without '@' symbol

2018 Dec 15, 6:53:08 PM

There is a trouble with symbol '&' in the code: "&&" is shown as "& Amp; & amp;"

2018 Mar 22, 9:29:36 AM

Mobile Beta

Get it on Google Play