CodesJava

Easy learning with example program codes

equals method in java

The equals() method in java is an Object class method. It return true for two non-null reference values x and y if and only if x and y refer to the same object. That means, basic implementation of equals method compares the memory location and not compare the object values.

Syntax:

public boolean equals(Object obj)

Java equals method example

package com.codesjava;
 
public class Test {
	public static void main(String args[]){
		String str1 = "codesjava";
		String str2 = "codesjava";
		//Return true, compare reference
		System.out.println(str1.equals(str2));
 
		String str3 = new String("codesjava");
		String str4 = new String("codesjava");
		//Return true, compare reference
		System.out.println(str3.equals(str4));
 
		Site site1 = new Site("codesjava", 1);
		Site site2 = new Site("codesjava", 1);
		//Return false, compare reference
		System.out.println(site1.equals(site2));		
	}
}
 
class Site{
	private String name;
	private int id;
 
	public Site(String name, int id) {
		super();
		this.name = name;
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
}

Output

true
true
false
Please follow and like us:
error
Posted in Java   








Copyright © 2019 CodesJava DMCA.com Protection Status