Java treats strings as String objects. Using strings as built-in object processing allows Java to provide a wealth of features for processing strings.
Public class MainClass {
Public static void main (String [] arg ){
String a = "";
String B = "";
If (a. equals (B )){
System. out. println ("a = B ");
} Else {
System. out. println ("! = B ");
}
}
}
Instance 2
Public class MainClass {
Public static void main (String [] arg ){
String a = "";
String B = "";
If (a. equalsIgnoreCase (B )){
System. out. println ("a = B ");
} Else {
System. out. println ("! = B ");
}
}
}
String length and position
Class StringDemo2 {
Public static void main (String args []) {
String strOb1 = "First String ";
String strOb2 = "Second String ";
String strOb3 = strOb1;
System. out. println ("Length of strOb1:" +
StrOb1.length ());
System. out. println ("Char at index 3 in strOb1:" +
StrOb1.charAt (3 ));
If (strOb1.equals (strOb2 ))
System. out. println ("strOb1 = strOb2 ");
Else
System. out. println ("strOb1! = StrOb2 ");
If (strOb1.equals (strOb3 ))
System. out. println ("strOb1 = strOb3 ");
Else
System. out. println ("strOb1! = StrOb3 ");
}
}
Notes
People familiar with C ++ must be familiar with the code for comparing two strings:
(String1 = string2)
However, in java, this code returns false even if the two strings are identical.
In Java, string1.equals (string2) must be used for judgment.
If:
String s1 = new String ("Hello ");
String s2 = new String ("Hello ");
Then (s1 = s2) = false
If:
String s1 = "Hello ";
String s2 = "Hello ";
Then (s1 = s2) = true;
If the values of other variables are assigned to s1 and s2, false is returned even if the content is the same because it does not point to the same object. Therefore, we recommend that you use equals () because equals compares the actual content.