java string - string 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: java how to compare strings
System.out.println("hey".equals("hey")); //prints true
/*
always use .equals() instead of ==,
because == does the compare the string content but
loosely where the string is stored in.
*/
Example 3: java == vs equals
In general both equals() and == operator in Java are used to compare
objects to check equality but here are some of the differences between the two:
1) .equals() and == is that one is a method and other is operator.
2) We can use == operator for reference comparison (address comparison)
and .equals() method for content comparison.
-> == checks if both objects point to the same memory location
-> .equals() evaluates to the comparison of values in the objects.
3) If a class does not override the equals method, then by default it
uses equals(Object o) method of the closest parent class
that has overridden this method.
// Java program to understand
// the concept of == operator
public class Test {
public static void main(String[] args)
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
Output:
false
true
Explanation: Here we are creating two (String) objects namely s1 and s2.
Both s1 and s2 refers to different objects.
-> When we use == operator for s1 and s2 comparison then the result is false
as both have different addresses in memory.
-> Using equals, the result is true because its only comparing the
values given in s1 and s2.
Example 4: how to check to string are qual r not
String str1 = "rohith";
String str2 = "nikhil";
//compares if str1(rohith) is equal to str2(nikhil)
System.out.println(str1.equals(str2));
//prints false as str1!=str2
Example 5: string java
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
Example 6: string in java
In java, string is an object. It is sequence of character values enclosed by
double quotes.