Java Classic Instance--connection string

Source: Internet
Author: User
String

Question: Connect some strings
Way to solve the problem:
Three ways:
1, directly with the + number connection, the compiler will construct a StringBuffer object, and call its Append method
2. Construct the StringBuffer object yourself, and the Append () method returns a reference to the StringBuffer object itself.
3, through the ToString method
Code:
/**
* Stringbufferdemo: Construct the same string in three different ways
*/
public class Stringbufferdemo {
public static void Main (string[] argv) {
String S1 = "Hello" + "," + "world";
System.out.println (S1);
  
Constructs the StringBuffer object and adds some strings
StringBuffer SB2 = new StringBuffer ();
Sb2.append ("Hello");
Sb2.append (', ');
Sb2.append (");
Sb2.append ("World");
  
Converts the StringBuffer value to a string and outputs
String s2 = sb2.tostring ();
SYSTEM.OUT.PRINTLN (S2);
  
Now repeat the above work, but in a more concise way
Typical "Real-world" JAVA
  
StringBuffer SB3 = new StringBuffer (). Append ("Hello").
Append (', '). Append ('). Append ("World");
System.out.println (Sb3.tostring ());
  
}
}
  
Summary: In fact, regardless of how many characters are modified in the StringBuffer, all methods append (), delete (), Deletecharat (), insert (), replace (), reverse () And so on, only returns the reference of the StringBuffer object, which is very advantageous for programming.



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.