Comparing String Values with Equals and ==

package Equalsand_Twoequals;

public class StringCompare {

	public StringCompare() {
		// TODO Auto-generated constructor stub
	}
	public static void main(String[] args) {
		String string1 = "sri";
		String string2 = "sri";
		String string3 = new String("sri");
		String string4 = new String("sri");
		
		System.out.println("EQUALS");
		System.out.println("------");
		System.out.println(string1.equals(string2));
		System.out.println(string1.equals(string3));
		System.out.println(string3.equals(string4));

		System.out.println("==");
		System.out.println("--");
		System.out.println(string1==string2);
		System.out.println(string1==string3);
		System.out.println(string3==string4);
	
		System.out.println("Imp One");
		System.out.println("-------");
		String string5 = new String("sri");
		String string6 = string5;
		System.out.println(string5.equals(string6));  //since string5 and string 6 are equal so true
		System.out.println(string5==string6); //since string5 and string 6 are equal so true // both in same memory location
		//
		System.out.println(string6==string3); //since string3 and string 6 are two different obj so false
		System.out.println(string6==string1); //since string1 and string 6 are two different obj so false
		
		
		String string7 = "sri";
		String string8 = string7;
		System.out.println(string8==string7);
		System.out.println(string8==string1);
		System.out.println(string8==string3);
	}
}

Output EQUALS —— true true true == — true false false Imp One ——- true true false false true true false

Leave a comment

Your email address will not be published. Required fields are marked *