The "Java" collation of the String class on Java, the difference between the equals and comparison operators

Source: Internet
Author: User

Beginner Java has a period of time, feeling seems to start into the door, have a bit of feeling but found a lot of confusion and doubts and all come from the most basic knowledge toss for a while to check the book, and finally to the String this special object has a bit of sentiment we first to see a strange program:
public class TestString {
public static void Main (string[] args) {
String S1 = "Monday";
String s2 = "Monday";
}
}
This app is really simple! But what's the problem?

1. From a String of concerns how many objects are there in this procedure?
Probably a lot of people blurt out: two, S1 and S2 why? The String is the final class, and its value is immutable. It seems to make sense, then to test it, a little change the program can see the results:
public class TestString {
public static void Main (string[] args) {
String S1 = "Monday";
String s2 = "Monday";
if (S1 = = s2)
System.out.println ("S1 = = s2");
Else
SYSTEM.OUT.PRINTLN ("S1! = s2");
}
}
Hehe, many people will say that there are more than two objects compiled and run the program, output: S1 = = S2 Ah!
why S1 = = s2?
= = Clearly is said: S1 and S2 reference the same String object-"Monday"!

2. The ever-changing string changes the program a little bit, and there are even more strange discoveries:
public class TestString {
public static void Main (string[] args) {
String S1 = "Monday";
String s2 = new String ("Monday");
if (S1 = = s2)
System.out.println ("S1 = = s2");
Else
SYSTEM.OUT.PRINTLN ("S1! = s2");
if (s1.equals (S2))
System.out.println ("S1 equals S2");
Else
System.out.println ("S1 not equals S2");
}
}
We will s2 create the program output with the new operator:
S1! = s2s1 equals s2
Well, it's obvious. S1 s2 references two "Monday" string objects respectively
But why are the two programs different?

3. Swimming in String swimming pool haha, turned over the book finally found the answer:
Originally, the program at run time will create a string buffer pool when using S2 = "Monday" expression is to create a string, the program first in this string buffer pool to find the same value of the object, in the first program, S1 was put into the pool, so when the S2 was created, The program found a S1 with the same value will s2 reference the object referenced by S1 "Monday" in the second paragraph of the program, using the new operator, he understood the tell the program: "I want a new!" Don't be old! "With a new" Monday "Sting object is created in memory. Their values are the same, but the locations are different, one swimming in the pool and one resting on the shore. Alas, it is a waste of resources, obviously the same must be divided into what?

4. Continue to dive again to change the program:
public class TestString {
public static void Main (string[] args) {
String S1 = "Monday";
String s2 = new String ("Monday");
S2 = S2.intern ();
if (S1 = = s2)
System.out.println ("S1 = = s2");
Else
SYSTEM.OUT.PRINTLN ("S1! = s2");
if (s1.equals (S2))
System.out.println ("S1 equals S2");
Else
System.out.println ("S1 not equals S2");
}
}
This time join: S2 = S2.intern ();
Wow! Program output: S1 = = s2 S1 equals s2 Originally, the program new S2, and intern () knocked him over the dominant haha, this time S2 and S1 have quoted the same object we succeeded in reducing the use of memory

5. = = battle with Equals ()
String is an object, to compare the value of two different string objects is the same as obvious to use Equals () this method but if there are so many string objects in the program, there are so many times to use Equals, oh, God, That's slow. Better way: Put all the strings intern () to the buffer pool it's best to do this when you use new, string s2 = new String ("Monday"). Intern (); Well, did everyone soak in the pool? Haha now I can use = = to compare the value of String object is really cool, fast and convenient!
String Ah string, let me say you what good? Isn't it enough for you to bring all the trouble to our Java programmers?
Look at String.

1. Look back at the bad temper of the String brother
Routine 1:class Str {
public static void Main (string[] args) {
String s = "hi!";
String t = "hi!";
if (s = = t)
System.out.println ("equals");
Else
System.out.println ("not equals");
}
}
What does the program output?
If the spectators have seen one of my "puzzles from String", I believe you will soon make the right decision: Program output: Equals

2. Oh, my God, it's mixing water again.
Routine 2:class Str {
public static void Main (string[] args) {
String s = "HELLO";
String t = s.touppercase ();
if (s = = t)
System.out.println ("equals");
Else
System.out.println ("not equals");
}
}
So what does this program output?
Careful! No more caution! Don't be fooled by String, the confused guy!
IT outputs: equalswhy!!!
Make a simple change to the program:
Class Str2 {
public static void Main (string[] args) {
String s = "Hello";
String t = s.touppercase ();
if (s = = t)
System.out.println ("equals");
Else
System.out.println ("not equals");
}
}
You might say, "Isn't it the same?" No! True, not the same! This time output:
Not EQUALSOH Mygod!!!
Who will teach this String?
3. Do you know your horse?
"To tame a runaway Mustang, you need to know its temperament," the cowboy said.
Do you know anything about String? To interpret the API of string, you can see that the toUpperCase () and toLowerCase () methods return a new string object that represents the uppercase or lowercase situation of the string, but note that if the original string itself is in uppercase or lowercase form, Then the original object is returned. This is why the second program S and T are entangled in the sake of this naughty, incorrigible String, there seems to be no better way to let us dissect it, to see what the structure of it:
(1) charAt (int n) returns the character of the n position within the string, the first character position is 0, the last character is the position of length ()-1, and the location of the access error throws a large brick: Stringindexoutofboundsexception is really big.
(2) concat (String str) joins a STR after the original object, but returns a new string object
(3) Equalsignorecase (String str) ignores the case of the Equals method the essence of this method is to first call the static character method toUpperCase () or toLowerCase () to convert the two characters compared, and then do the = = operation
(4) Trim () returns a new object that segmentation the beginning and end of the original object with the same whitespace, and returns the original object if there is no difference between the result and the original object
(5) the ToString () String class also has the ToString () method? It's an interesting question, but without it, your string object might not really be used in System.out.println (). Be careful, it returns the object itself string class there are many other methods, mastering them will bring a lot of convenience there will be a lot of confusion, So sticking to the principle is the most critical
4. I'm want to buy a better horse to buy more tame gentle String of the younger brother StringBuffer bar
There will be objections:
It is very useful, it is very efficient, how can it be a younger brother?
It's simple, it's less interactive than string, and if you want to edit the string it's not convenient, you'll be disappointed with it but that doesn't mean it's not strong public final class String implements Serializable, comparable, Charsequencepublic Final class StringBuffer implements Serializable, charsequence it's obvious, little brother, But it's not going to interfere with its future. StringBuffer is not inherited by String but pay attention to brother it is final ah, this is the same root to see his method, so many stable and reliable method, with more than naughty string to be more efficient? Java provides a separate StringBuffer class for a string object that needs to be changed its instances are immutable (final), because the modification of the string requires the system to increase the volume of sales, occupy more space is more complex, Believe that when there are 10000 people huddled in a small swimming pool and the shore and 10000 people waiting to enter the swimming pool and anxiously lit up with 10000 people watching the lively side, you the string pool of administrators will also be burned in the case you do not need to change the string, the simple string Class is enough for you to use, and when you want to change the contents of the string frequently, you need to rely on the Prime Minister Belly can punting StringBuffer
5. Prime Minister Belly can punting
(1) Length () and Capacity () in string () returns the lengths of the strings brother StringBuffer is also so, they are determined by the length of the characters contained by the object capacity ()?
public class Testcapacity {
public static void Main (string[] args) {
StringBuffer buf = new StringBuffer ("It is the age of Wisdom,");
System.out.println ("buf =" + buf);
System.out.println ("buf.length () =" + Buf.length ());
System.out.println ("buf.capacity () =" + buf.capacity ());
String str = buf.tostring ();
System.out.println ("str =" + str);
System.out.println ("str.length () =" + Str.length ());
Buf.append ("" + str.substring (0,18)). Append ("foolishness,");
System.out.println ("buf =" + buf);
System.out.println ("buf.length () =" + Buf.length ());
System.out.println ("buf.capacity () =" + buf.capacity ());
System.out.println ("str =" + str);
}
}
Program output:
BUF = It is the age of wisdom.buf.length () = 25
Buf.capacity () = 41
str = It is the age of wisdomstr.length () = 25
BUF = It is the age of wisdom, it is the age of foolishness,
Buf.length () = 56
Buf.capacity () = 84
str = It is the age of wisdom,
As you can see, after the content changes, capacity also changes the length as it adds characters to the string and the capacity increases only after the new length exceeds the current capacity StringBuffer Capacity is automatically changed when the operating system needs it. What the capacity can do is simply to initialize the StringBuffer object. http://blog.csdn.net/yiqunattack/article/details/5727143

The "Java" collation of the String class on Java, the difference between the equals and comparison operators

Related Article

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.