"Learning Notes" string Advanced: StringBuffer Class (thread safe) and StringBuilder class

Source: Internet
Author: User

In addition to using the string class to store strings, you can also use the StringBuffer class to store strings. And it is a reference data type that is more efficient than the string class to store strings.

Advantages:

When connecting strings, using the StringBuffer class can greatly improve the execution efficiency of the program.

1. How to use the StringBuffer class

The StringBuffer class is in the Java.util package and is an enhanced class of the String class. The method for declaring the StringBuffer object and initializing it is as follows:

StringBuffer sb = new StringBuffer ("Youth Without Regrets");

2, commonly used StringBuffer class method

(1), toString () method

String str = sb.tostring (); Convert to String class

(2), append () method

String. Append (parameters);

(3), insert (position, parameters);

Insert (); The method can be implemented to insert a parameter into the specified position of the string.

Case: Write a method that converts a numeric string to a comma-separated number of strings.

1  Public classInsertdemo {2 3      Public Static voidMain (string[] args) {4String nums = "123418447.6717";5StringBuffer words =NewStringBuffer (nums);6         //inserting a comma into a string7         intindex =words.length ();8         if(Words.lastindexof (".") >0) {9index = Words.lastindexof ("."));Ten         } One          for(inti = index-3; I >0; I=i-3) { AWords.insert (i, ', '); -         } - System.out.println (words); the  -     } -  -}

Analysis: Use the Length () method of the StringBuffer class to get the lengths of the strings, using a for loop to insert commas every three bits from the back forward.

Ii. Comparison of String class, StringBuilder class and StringBuffer class

1.String: String constants: Immutable objects, each assignment is equivalent to generating a new string object.

2.StringBuffer: String variable: A variable string.

3.StringBuider: String variable: JDK1.5 later available: Single thread out of sync.

Third, the application of StringBuffer class: Realize the display of the wholesale amount of goods

1 ImportJava.util.Scanner;2 3 /**4 * Display of total wholesale amount of merchandise5  * @authorAdministrator6  *7  */8  Public classGoods {9     //create an array to store the product name and the corresponding priceTenstring[] Goods =Newstring[]{"Fan", "Washing Machine", "TV", "refrigerator", "air conditioner"}; One     Double[] Price =New Double[]{124.23,4500,8800.90,5000.88,4456,12000.46}; A  -     //Login Verification -     Private BooleanLogin (string name, string pwd) { the         BooleanFlag =false; -         if(Name.equals ("TOM") &&pwd.equals ("123"))) { -System.out.println ("Landing success!") "); -Flag =true; +}Else{ -System.out.println ("User name and password do not match! "); +         } A         returnFlag; at     } -     //Print product Information -     Private voidShow () { -         //1. Save using the Map collection -          -         //2. Print using the General method inSYSTEM.OUT.PRINTLN ("************* Welcome to the commodity wholesale City *************"); -System.out.println ("\ t number \ t product \ t Price"); to          for(inti = 0; i < goods.length; i++) { +System.out.println ("\ T" + (i+1) + "\ T" +goods[i]+ "\ T" +price[i]); -         } theSystem.out.println ("****************************************"); *     } $     Panax Notoginseng     //Calculate order Total Price -     Private DoubleCalcintGoodid,intsum) { the         //Find product information by product number +         intindex = goodId-1; A         DoubleSumprice =-1; the         if(Index>=0&&index <goods.length) { +Sumprice = price[index]*sum; -}Else { $SYSTEM.OUT.PRINTLN ("The item you have selected does not exist!") "); $         } -         returnSumprice; -     } the  -     //formatted output amountWuyi     Private BooleanChangeintGoodid,intsum) { the         //Call the Calc () method to get the item amount -         DoubleD = This. Calc (goodid, sum); Wu         BooleanFlag =false;//product does not exist -         if(D==-1) { About             returnFlag; $         } -StringBuffer Price =NewStringBuffer (string.valueof (d)); -          for(inti = Price.indexof (".") -3; i > 0; i = i-3) { -Price.insert (i, ', '); A         } +SYSTEM.OUT.PRINTLN ("You need to pay:" +Price ); the         returnFlag =true; -     } $  the     //Test the      Public Static voidMain (string[] args) { theGoods g =NewGoods (); the@SuppressWarnings ("Resource") -Scanner input =NewScanner (system.in); in         BooleanFlag =false; the          Do { the             /*User Login*/ AboutSystem.out.print ("Please enter user name:"); theString name =Input.next (); theSystem.out.print ("Please Enter password:"); theString pwd =Input.next (); +Flag =g.login (name, pwd); -} while(!flag); the         //Print Wholesale Product informationBayi g.show (); theFlag =false; the          Do { -             //receive user wholesale operation -System.out.print ("Please enter your wholesale product number:"); the             intGoodid =input.nextint (); theSystem.out.print ("Please enter wholesale quantity:"); the             intsum =input.nextint (); the             //Total Output Payment -Flag =G.change (goodid,sum); the} while(!flag); the          the     }94  the}

"Learning Notes" string Advanced: StringBuffer Class (thread safe) and StringBuilder class

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.