Java string comparison

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.