1. How do you compare two strings in Java? Explain with example.
We can compare String in Java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.
There are three ways to compare String in Java:
By Using equals() Method
By Using == Operator
By compareTo() Method
By Using equals() Method
The String class equals() method compares the original content of the string. It compares values of string
for equality.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2)); true
System.out.println(s1.equals(s3)); true
System.out.println(s1.equals(s4)); false
}
}
By Using == Operator
The == operator compares references not values.
class Teststringcomparison3{
,public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2); true (because both refer to same instance)
System.out.println(s1==s3); false(because s3 refers to instance created in nonpool)
}
}
By compareTo() Method
The String class compareTo() method compares values lexicographically and returns an integer
value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two String objects. If:
s1 == s2 : The method returns 0.
s1 > s2 : The method returns a positive value.
s1 < s2 : The method returns a negative value.
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2)); 0
System.out.println(s1.compareTo(s3)); 1(because s1>s3)
System.out.println(s3.compareTo(s1)); -1(because s3 < s1)
}
}
, 2. How to declare a string in Java? Explain with example.
String is a sequence of characters. But in Java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create a string object.
There are two ways to create String object:
1. By string literal
2. By new keyword
By String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object
with the value "Welcome" in string constant pool that is why it will create a new object. After that