string equals java code example

Example 1: Java compare two strings

// compare two strings in java using String.equals() method in java
public class EqualsMethodDemo
{
   public static void main(String[] args)
   {
      String str1 = new String("HelloWorld");
      String str2 = new String("Flower");
      String str3 = new String("Hello");
      String str4 = new String("Hello");
      String str5 = new String("hello");
      // compare str1 != str2
      System.out.println("Compare " + str1 + " and " + str2 + ": " + str1.equals(str2));
      // compare str3 = str4
      System.out.println("Compare " + str3 + " and " + str4 + ": " + str3.equals(str4));
      // compare str4 != str5
      System.out.println("Compare " + str4 + " and " + str5 + ": " + str4.equals(str5));
      // compare str1 != str4
      System.out.println("Compare " + str1 + " and " + str4 + ": " + str1.equals(str4));
   }
}

Example 2: string compare java ==

// These two have the same value
new String("test").equals("test") // --> true 

// ... but they are not the same object
new String("test") == "test" // --> false 

// ... neither are these
new String("test") == new String("test") // --> false

Example 3: java not equal to

if(5 != 4) // != means "not equal to"
  	return true;

Example 4: 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);
		
	}

}

Example 5: how to know if String is the same java

String1.equals(String2)

Tags:

Misc Example