Java reading note Three (string)

Source: Internet
Author: User

1. Introduction

This blog will introduce the basics of string classes in Java. Some of the most common uses of the main string class.


2. Creation of String objects

1. There are two kinds of forms. However, in development, it is often used in the form of string variable names to operate.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package com. String;public class Sample13_1 {public static void main (string args[]) {//Use simple syntax to create string object strings S1= "Java Core technology Daquan welcome you!! ";//Use the constructor to create a string object. String S2=new string (" Congratulations you have created the string in two different syntaxes.) ");//Create an empty string object string s3=" ";//The value of string reference S4 is nullstring s4=null;//print content System.out.println (s1+" # "+s2+" # "+s3+" # "+S4);}} </span>


some important methods of the 2.String class

string as the identity of an object appears, there must be some way to manipulate the string, frequently used methods such as the following summary.

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package com. String;public class Sample13_3 {public static void main (string args[]) {string S1 = "JavaSE6.0 core technology Daquan Welcome!! "; String s2 = new String ("Congratulations on creating a string with two different syntaxes.) "); String s3;//uses the CharAt method to get a character in a string System.out.println ("=====================charat======================="); char C = S1.charat (4); System.out.println ("Start from 0. The 4th character in the string S1 is: "+ c);//Use the ToCharArray method to convert a string to a character array System.out.println (" =====================tochararray============ ====== "); char[] array = S1.tochararray (); System.out.print ("Print the char Array backwards:"); for (int i = array.length-1; I >= 0; i--) System.out.print (Array[i]);//Use concat method to connect Two strings of System.out.println ("\n=====================concat======================="); s3 = S1.concat (S2); SYSTEM.OUT.PRINTLN ("The result of connecting two strings is:" + s3);//Use the Equals method to compare the contents of a two string System.out.println ("=====================equals= ====================== "); s3 =" JavaSE6.0 Core technology Daquan welcome you!!

; if (S1.equals (S3)) System.out.println ("Congratulations on your test success.") The content of S1 and S3 is exactly the same!. ")///Use the Equalsignorecase method to compare the contents of two strings without distinguishing between uppercase and lowercase System.out.println (" =================equalsignorecase========= ======== "); s3 =" JAVASE6.0 Core technology Daquan welcome you!!

"; if (S1.equalsignorecase (S3)) System.out.println (" S1 and S3 are the same in cases where uppercase and lowercase are not distinguished!. ")///Use the length method to get a string of System.out.println (" ======================length====================== "); int size = S1.length (); System.out.println ("The number of characters in the S1 is:" + size);//Use the Replace method to replace a character in a string System.out.println ("======================replace ===================== "); s3 = S1.replace (' A ', ' X '); SYSTEM.OUT.PRINTLN ("Replace all letters A in S1 with the letter x:" + s3);//Use the substring method to get a substring of the string System.out.println ("====================== substring=================== "); s3 = S1.substring (10); System.out.println ("Start from 0. The 10th character in the S1 string is: "+ s3); s3 = S1.substring (2, 10); System.out.println ("Starting from 0, S1 the 2nd character to the 10th character string is:" + s3);//Use the toLowerCase method to convert the character embox of a string to lowercase System.out.println ("======== ==============tolowercase================= "); s3 = S1.tolowercase (); SYSTEM.OUT.PRINTLN ("Change the word embox in S1 to lowercase:" + s3);//Use the toUpperCase method to convert the character embox of a string to uppercase System.out.println ("====================== touppercase================= "); s3 = S1.touppercase (); System.out.println ("Convert the word embox in S1 to uppercase:" + s3);//Use the Trim method toThe Invisible character System.out.println ("======================trim========================") of the string header and tail is dropped; s3 = "Java SE6.0 "; System.out.println ("S3 no practical Trim method before: [" + S3 + "]"); s3 = S3.trim (); System.out.println ("S3 after Trim method: [" + S3 + "]");}} </span>



Memory mechanism for 3.String objects

The string object has "one input." The benefits of lifelong returns. Here's a piece of code to analyze first

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" >package com. String;public class Sample13_4 {public static void main (string args[]) {//Use simple syntax to create a string S1 with s2string S1 = "JavaSE6.0"; String s2 = "JavaSE6.0";//Use the constructor to create a string s3string s3 = new String ("JavaSE6.0");//Use = = Comparison string S1 with s2if (S1 = s2) {System.out.prin TLN ("string S1 with string s2 passed equals test, result returns true");} else {System.out.println ("string s1 and string s2 not passed equals test. The result returns false ");} Use = = Comparison string S1 with s3if (S1 = = S3) {System.out.println ("string S1 with string S3 passed equals test. The result returns true ");} else {System.out.println ("string S1 with string S3 does not pass equals test, Result returns false");} Use the Equals method to compare strings S1 with S3if (S1.equals (S3)) {System.out.println ("string S1 with string S3 content, the result returns true");} else { System.out.println ("string S1 differs from string s3, Result returns false");}}} </span>


If you agree with the above example, there will be unexpected results. Simply analyze the memory mechanism of the string below.

When the JVM executes, it divides the memory into two parts, one is the heap, the other is the stack, the object is placed in the heap, and the object's reference or local variable is placed in the stack. Java is in memory design. It also opens up a very small memory in the heap, called a constant pool of strings, to hold a particular string object.

When you use string s1= "xxxx" to create. Will first look at whether the constant pool is already included. Suppose there is. Simply point the reference to it.

watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbhvja3l6ag91c3rhcg==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma== /dissolve/70/gravity/center ">

So when performing the above example. Wouldn't be surprised. By this design, the string was compared when it was created. It is only necessary to compare the two references to the same object.

It is important to note that a string object created with new will create a string object directly on the heap without this effect.


3.StringBuffer class

The string class is described above. However, there are shortcomings, assuming that the string concatenation of strings, memory consumption will be very large, so in order to compensate for the lack of string, StringBuffer appeared.

By StringBuffer when stitching a string. No intermediate objects are produced. So when you need to make a lot of connections to strings, you should use the StringBuffer class

The regular usage of the StringBuffer class such as the following

<span style= "font-family:simsun;font-size:18px;" >package com. String;public class Sample13_10 {public static void main (string[] args) {StringBuffer sb1 = new StringBuffer ("Java6.0"); System.out.println ("The contents of the object SB1 before the operation are:" + SB1);//SB1 a series of operations Sb1.append ("Core technology Daquan"). Insert (4, "SE"). Delete (9,.). Reverse (); System.out.println ("The contents of object SB1 after a series of actions are:" + SB1);//create content with SB1 same StringBuffer object Sb2stringbuffer SB2 = new StringBuffer ( Sb1.tostring ());//Use the Equals method of StringBuffer to test System.out.println ("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = if (Sb1.equals (SB2)) {System.out.println ("Object SB1 and SB2 content same!! 

. ");} else {System.out.println ("Object SB1 is not the same as SB2 's content!

!!

"); Using the ToString method, use the Equals method to test the System.out.println ("= = = Use the Equals method after using the ToString method to test the contents of the object sb1 and SB2 = ="); String S1 = sb1.tostring (); String s2 = sb2.tostring (), if (s1.equals (S2)) {System.out.println ("Object SB1 is the same as SB2 's content!

! ");} else {System.out.println ("Object SB1 is not the same as SB2 's content!

. ");}}} </span>



4.StringBuilder class

The StringBuilder class is similar to the StringBuffer class, and can be used to make a large number of string concatenation operations.


The difference between 5.StringBuilder and StringBuffer

1. First of all, the efficiency of StringBuilder is higher than that of the StringBuffer class. However, the string editing methods of the StringBuilder class do not synchronize, which can cause problems in multi-threading.

2.StringBuffer does not cause problems when multi-threading, because the editing of the string is synchronized



Java reading note Three (string)

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.