equal string java code example

Example 1: java string equal vs ==

Case1)
String s1 = "Stack Overflow";
String s2 = "Stack Overflow";
s1 == s1;      // true
s1.equals(s2); // true
Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
Case2)
String s1 = new String("Stack Overflow");
String s2 = new String("Stack Overflow");
s1 == s2;      // false
s1.equals(s2); // true
Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.

Example 2: equals example java

import java.util.Scanner;

public class YourProjectName {

	public static void main(String[] args) {
		Scanner keyboard = new Scanner(System.in);
		
		//D
		
		String password1;
		String password2;
		String msg;
		
		//E
		
		System.out.println("Enter password: ");
			password1 = keyboard.nextLine();
		
		System.out.println("Repeat password: ");
			password2 = keyboard.nextLine();
		
		//P
		
		if (password1.equals(password2)) {
			msg = "Password matching!";
		} else {
			msg = "Password not match";
		}
		
		//S
		
		System.out.println(msg);
		
	}

}

Tags:

Java Example