Java Foundation 4:string and StringBuffer and basic data type wrapper class

Source: Internet
Author: User


On the Java Foundation of the article, I think it can also be written in my other blog, is definitely original, and now share to everyone out.

----------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------


Some of the underlying classes in Java such as String, StringBuffer, and basic data type wrapper classes are very common and very frequently used classes. Although these classes are simple, they also have to be learned in order to be proficient, although the API documentation is more detailed about the use of these classes, but I think it is necessary to tidy them up.

First, the String class

1. Overview

String is the meaning of strings, the first thing to be clear is that string does not belong to the base data type.

Because the default value of the object is NULL, the default value of string is also null, but it is a special object that has some features that other objects do not have.

Note that the new string () and NewString ("") all declare an empty string instead of NULL.

Once the string is initialized, it cannot be changed.

2. Initialize

Object Initialization format string s = new String ("abc");

----can be abbreviated as string s = "abc";

3. String constant Pool

Before we start, let's first look at an example.

Example 1      String s1 = "abc";      String s2 = "abc";      String s3 = "a" + "BC";      System.out.println (S1 = = s2);   True      System.out.println (S1 = = s3);//TRUE//Example 2 string s1 = new String ("abc");  String s2 = new String ("abc");  String s3 = "a" + new String ("BC");  System.out.println (S1==S2);        False  System.out.println (S2==S3);        

Running the results of this 2 example, we will be surprised to find that example 1 and Example 2 run a different result. Does it mean the same as new and not new?

Here we are going to introduce the concept of a constant pool: Chang (constant pool) refers to some data that is determined at compile time and saved in the compiled. class file. It includes constants in classes, methods, interfaces, and so on, and also includes string constants.

Java ensures that there is only one copy of a string constant.

Because the "ABC" in the example S1 and S2 are string constants, they are determined at compile time, so s1==s2 is true;

Strings created with new string () are not constants and cannot be determined at compile time, so the strings created by new string () are not placed in the constant pool, they have their own address space.

4. Common methods

4.1. Get:

4.1.1 Gets the number (length) of characters in the string.

int length ();

4.1.2 Gets the character based on its location.

char charAt (int index);

4.1.3 Gets the position of the first occurrence in the string, based on the character.

int indexOf (int ch) CH is the Unicode encoding of the character

int indexOf (int ch,int fromIndex) Find the first occurrence of CH from a specified position

The int indexOf (string str) Gets the position of the first occurrence in the string based on the string.

The int indexOf (string str,int fromIndex) obtains the position of STR in the string, starting at the FromIndex specified position.

4.1.31 Reverse index, looking forward from behind

int lastIndexOf (int ch)

int lastIndexOf (int ch,int fromIndex): Find the first occurrence of CH from the specified position

int lastIndexOf (String str);

int lastIndexOf (String str,int fromIndex);

4.1.4 gets the string substring.

String substring (int beginindex, int endIndex)//contains begin does not contain end.

string substring (int beginindex);//The string is truncated starting at the Beiginindex index.

4.2. Conversion

4.2.1 string into a string array

String[] Split (String regex): A regular expression is involved.

4.2.2 the string into a character array.

Char[] ToCharArray ();

4.2.3 the string into a byte array.

Byte[] GetBytes ();

4.2.4 converts the letters in a string to case.

String toUpperCase (): Uppercase

String tolowercase (): lowercase

4.2.5 to replace the contents of a string

String replace (char Oldch,char newch);

String Replace (string s1,string s2);

2.6 Remove the spaces at both ends of the string.

String trim ();

2.7 Connect the string.

String concat (String);

4.3. Comparison of Judgments

4.3. Are the contents of 12 strings the same?

Boolean equals (Object obj);

Boolean equalsignorecase (String str), ignoring uppercase comparison string contents.

4.3.2 does the string contain the specified string?

Boolean contains (string str);

4.3.3 whether the string begins with the specified string. Whether to end with the specified string.

Boolean StartsWith (String);

Boolean EndsWith (String);

Second, StringBuffer class

1. Overview

The StringBuffer class, like String, is also used to represent strings, except that because the StringBuffer is implemented in a different way than string, the StringBuffer does not generate a new object when string processing occurs. The memory usage is superior to the string class.

So in the actual use, if you often need to modify a string, such as inserting, deleting and so on, use StringBuffer to be more appropriate.

There are many methods in the StringBuffer class that are the same as the string class, which are functionally identical to the functions in the string class.

One of the most notable differences, however, is that each modification of a StringBuffer object alters the object itself, which is the biggest difference from the string class.

2. Stirngbuffer initialization

The initialization of the StringBuffer object is not the same as the initialization of the string class, Java provides special syntax, and typically is initialized with a constructor method.

3. Features

A, the length of the variable.

B. You can store different types of data.

C, the final to be converted into a string to use.

D, you can modify the string.

4. Common methods

4.1 Add:

StringBuffer append (data);//ability to add various types

StringBuffer Insert (Index,data); Insert various types in the index

4.2 Delete:

StringBuffer Delete (Start,end): Contains the header, does not contain the tail.

StringBuffer deletecharat (int index): Deletes the element at the specified position

4.3 Find:

Char charAt (index); The char value out of the index

int Codepointat//character at index

int indexOf (string); //

int lastIndexOf (string);

int capacity ()//returns the capacity of the current buffer (initial 16)

int length ()//length

4.4 Modifications:

StringBuffer replace (start,end,string);

void Setcharat (Index,char);

StringBuffer reverse () replaces this sequence of characters with its inverse form (there is no reversal in the string class)

void TrimToSize () attempts to reduce the storage space used for character sequences.

5, StringBuilder

After the jdk1.5, the object with the same function and StringBuffer appeared. It's StringBuilder.

This is not covered in detail here. It would be nice to take a look at their differences.

The difference is:

The StringBuffer is thread-synchronized. Typically used for multithreading.

StringBuilder is a thread that is not synchronized. Typically used for single threads. Its appearance improves efficiency.

Three, basic data type packing class

1. Overview

The Java language is an object-oriented language, but the basic data types in Java are not object-oriented, which in the actual use of a lot of inconvenience, in order to solve this shortcoming, in the design of the class for each basic data type to design a corresponding class to represent, The classes that correspond to the eight basic data types are collectively referred to as wrapper classes.

2. Correspondence relationship

Byte--byte

Short--short

Int--integer

Long-----Long

Float-----Float

Double----Double

Char----Character

Boolean---Boolean

3, Integer class internal common methods

In fact, these kinds of data types in the packaging is similar, I only take the integer as an example to introduce briefly.

A, parseint method

Converts a numeric string to an int value. String s = "123"; int n = integer.parseint (s);

The string "120" is converted to int by decimal, then the result is an int n = integer.parseint ("120", 10);

The string "12" is converted to int by 16, then the result is an int n = integer.parseint ("12", 16);

Converting the string "FF" to int by 16, the result is 255 int n = integer.parseint ("FF", 16);

b, int to string

You can connect directly with the + sign, or you can use the ToString function.

Converts the int type to the corresponding string type. int m = n; String s = integer.tostring (M);

c, decimal into other binary.

Tobinarystring ();

Tohexstring ();

Tooctalstring ();

Iv. final

Even simple things, we have to pay attention to it, adhere to a little progress every day, and finally we are successful.

Java Foundation 4:string and StringBuffer and basic data type wrapper class

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.