Difference between == and equals() method in Java

HOME

What is == operator ?

To compare primitives and objects we use “==” equality operator in java which is a binary operator given in the java programming language

What is equals() method in java?

The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

Difference between == and equals method in java

1. == is an operator whereas equals() is a method of Object class.

2. == operator compares reference or memory location of objects in the heap, whether they point to the same location or not. Whenever we create an object using the operator new it will create a new memory location for that object. So we use the == operator to check memory location or address of two objects are the same or not.
equals() method  is used to compare the state of two objects or the contents of the objects.

3. Equals method can be overridden but you can’t override behavior of “==” operator.

Below is an example which shows the use of == and equals.

public class EqualsDemo1 {

	public static void main(String[] args) {
		String str1 = new String("JAVATUTORIAL");
		String str2 = new String("JAVATUTORIAL");

		// Reference comparison
		System.out.println("Check str1 == str2 : " + (str1 == str2));

		// Content comparison
		System.out.println("Check str1.equals(str2) : " + str1.equals(str2));

		// integer-type
		System.out.println("Check Integer Type :" + (10 == 10));

		// char-type
		System.out.println("Check Char Type :" + ('a' == 'a'));
	}
}

Output
Check str1 == str2 : false
Check str1.equals(str2) : true
Check Integer Type :true
Check Char Type :true

Let us take an example where both strings have same characters and same length but in lower case.

public class EqualsDemo2 {

	public static void main(String[] args) {
		String str1 = new String("JAVATUTORIAL");
		String str2 = new String("jAVATUTORIAL");

		// Reference comparison
		System.out.println("Check str1 == str2 : " + (str1 == str2));

		// Content comparison
		System.out.println("Check str1.equals(str2) : " + str1.equals(str2));
	}
}

Output
Check str1 == str2 : false
Check str1.equals(str2) : false

Let us take an example where both Integer refer to the same object.

public class EqualsDemo3 {

	public static void main(String[] args) {

		Integer i = new Integer(10);
		Integer j = i;

		System.out.println("Check i == j : " + (i == j));
}

Output
Check i == j : true

Let us take an example where both Integer1 and Integer2 refer to the different objects.

public class EqualsDemo4 {

	public static void main(String[] args) {

		Integer i = new Integer(10);
		Integer j = new Integer(10);

		System.out.println("Check i == j : " + (i == j));
	}
}

Output
Check i == j : false

That’s it for today. Have a wonderful learning.

Strings Manipulation in Java

HOME

 

public class String_Demo {
       public static void main(String[] args) { 

              //creating string by java string literal
              String str1 = "learn";
              char[] message = {'b','a','s','i','c'};

              //creating string by new keyword
              String str2 = new String(message);
              String str3 = new String("java");
              System.out.println(str1);
              System.out.println(str2);
              System.out.println(str3);
       }
   }
 
  Output
  learn
  basic
  java

 

Java String Manipulation

1.  length() 

returns the number of characters in the string. It counts every alphanumeric char, special char or even spaces.

   public class String_Demo {
       public static void main(String[] args)  {
              String message = "Learn Basic Java";
              int Str_Len= message.length();
              System.out.println("Length of String is : " + Str_Len);   
       }            
   }

  Output
   Length of String is : 16

2.  Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation. You can also use this method to concatenate two strings. Java uses the + operator for both addition and concatenation.

 Numbers are added. Strings are concatenated.

public class String_Demo {
       public static void main(String[] args) {
              String message_1 = "Learn Basic Java";
              String message_2 = "and Learn Selenium";
              String  Concat_message= message_1 +" "+ message_2;
              System.out.println("Concatenation Result is : " + Concat_message);
       }
  }

Output
Concatenation Result is : Learn Basic Java and Learn Selenium

3.  equals()

It compares two strings lexicographically, ignoring case differences.

 public class String_Demo {
       public static void main(String[] args) {
              String message_1 = "Learn Basic Java";
              String message_2 = "Learn Selenium";
              boolean CompareResult = message_1.equals(message_2);
              System.out.println("The result of String Comparison is : " + CompareResult);
         }
   }

  Output
  The result of String Comparison is : false

4.  equalsIgnoreCase()

It compares two strings lexicographically, ignoring case differences.

public class String_Demo {
	public static void main(String[] args) {
		String message_1 = "selenium";
		String message_2 = "SELENIUM";
		boolean comp_ignore_case = message_1.equalsIgnoreCase(message_2);
		System.out.println("The result of String Comparison after ignoring case difference is : " + comp_ignore_case);
	}
}


Output
The result of String Comparison after ignoring case difference is : true

5.  CharAt()

It returns the character located at the specified index.

public class String_Demo {
    public static void main(String[] args) {
           String message = "Learn Basic Java";
           char cIndex = message.charAt(6);
           System.out.println("The fifth character of Popular Topic 1 is : " + cIndex);
       }
}

 Output
 The fifth character of Popular Topic 1 is : B

6.  toLowerCase() 

It returns the string in lowercase letters.

     public class String_Demo {
    public static void main(String[] args) {
          String message = "Learn Basic Java";
          String lower_case= message.toLowerCase();
          System.out.println("The message in lower case is : " + lower_case);
     }
}

Output
The message in lower case is : learn basic java

7.  toUpperCase()  

It converts all the characters in the String to upper case.

public class String_Demo {
    public static void main(String[] args) {
           String message = "Learn Basic Java";
           String upper_case= message.toUpperCase();
           System.out.println("The message in upper case is : " + upper_case);
      }
 }
 
Output
The message in upper case is : LEARN BASIC JAVA

8.   trim() 

This method returns a copy of the string, with leading and trailing whitespace omitted.

public class String_Demo {
    public static void main(String[] args) {
           String message =" Java ";
            int len_1 = message.length();
            System.out.println("Length of message before trimming white spaces is : " + len_1);
            String message_2 = message.trim();
            int len_2 = message_2.length();
            System.out.println("Message after trimming white spaces is : " + message_2+" and length is "+len_2);
       }
  }

Output
 Length of message before trimming white spaces is : 6
 Message after trimming white spaces is : Java and length is 4

9.   replace() 

It replaces occurrences of a character with a specified new character.

public class String_Demo {
	public static void main(String[] args) {
           String str = "Java";
           System.out.println(str.replace('v','V'));
      }
}

Output 
JaVa

10.  split(String regex)

It splits this string against a given regular expression and returns a String array.

public class String_Demo {
	public static void main(String[] args) {
		String message = "Learn Basic Java";
		String[] aSplit = message.split("Basic");
		System.out.println("The first part of the array is : " + aSplit[0]);
		System.out.println("The last part of the array is : " + aSplit[1]);
	}
}
 
Output
The first part of the array is : Learn 
The last part of the array is :  Java

11.  startsWith(String prefix)  

Tests if the string starts with the specified prefix.  It returns true if the character sequence represented by the argument is a prefix of the character sequence represented by this string; false otherwise.

public class String_Demo {
	public static void main(String[] args) {
		String str = "Java";
		System.out.println("Result is " + str.startsWith("co"));
	}
}

Output
Result is false

12.  indexOf(String str)

It returns the index within this string of the first occurrence of the specified substring.

public class String_Demo {

	public static void main(String[] args) {
		
		String message = "This is an example of a test framework of Selenium";
		int firstIndex = message.indexOf("of");
		System.out.println("The start index is : " + firstIndex);
	}
}


Output
The start index is : 19

13.  lastIndexOf(String str)

It returns the index within this string of the last occurrence of the specified substring.

public class String_Demo {

	public static void main(String[] args) {
		
		String message = "This is an example of a test framework of Selenium";
		int lastIndex = message.lastIndexOf("of");
		System.out.println("The last index is : " + lastIndex);
	}
}

Output
The last index is : 39

14. substring()  

It returns a part of the string.

public class String_Demo {
	public static void main(String[] args) {
		String message = "Learn Basic Java";
		String sSubString = message.substring(5, 12);
		System.out.println("The sub string of Popular Topic 1 from index 5 to 11 is : " + sSubString);
	}
}

Output
The sub string of Popular Topic 1 from index 5 to 11 is :  Basic 

15. contains(CharSequense s)

It returns true if and only if this string contains the specified sequence of char values.

public class String_Demo {

	public static void main(String[] args) {

		String message = "This is an example of a test framework of Selenium";
		boolean containsExample = message.contains("example");
		System.out.println("The string conatins example : " + containsExample);
	}
}

Output
The string conatins example : true