Java Learning Note (ii): String

Source: Internet
Author: User
Tags locale

String

In Java, string is a data type that exists as a reference object and is used to hold a string.

instantiating and assigning values
// Direct Declaration String S1 = "Hello world!" ; // created by a constructor that provides methods for creating 11 different parameters Char [] c = {' H ', ' e ', ' l ', ' l ', ' o ', '. '  New String (c);

The string class is immutable, so once you create a string object, its value cannot be changed. If you need to make a lot of changes to the string, you should choose to use the StringBuffer or StringBuilder class.

Let's look at another way to create this:

Using this method to create a string, two string objects are created in heap memory, because when the "" symbol is used to create a new string, and Str points only to the second object, which causes the first object to have no reference and is in the state of waiting to be reclaimed, it increases the burden of the GC in addition to increasing memory usage. So it's a better way to use "" to create strings directly.

Connection string

The string class provides a way to concatenate two strings:

String1.concat (string2);

Returns a new string for the string2 connection string1. You can also use the concat () method on string constants, such as:

"My name is". Concat ("Zara");

It is more commonly used to concatenate strings using the ' + ' operator, such as:

"Hello," + "world" + "!"

The results are as follows:

"Hello, world!."

Here is an example:

1  Public class Stringdemo {2     Public Static void Main (String args[]) {     3    string string1 = "Saw I was";      4    System.out.println ("Dot" + string1 + "Tod");   5 }6 }

The results of the above example compilation run as follows:

Dot saw I was Tod

Comparing strings

Determine whether the string content is equal, Java is not the same as most languages, Java = = is a comparison of two strings referenced by the same address, that is, whether to point to the same object, and the Equals method compares the contents of the string is the same.

String a = "abc"new String ("abc");

A = = B returns false,a.equals (b) returns True. At this point when B is created, regardless of whether "ABC" is present, new "ABC", so that A and B point to the character of the object is different, so return false.

Let's look at the following situation, which is easy to confuse:

String a = "abc"= "abc";

A = = B returns true,a.equals (b) also returns True, which is why?

The original program has a string pool at run time, when the string is created, it looks for the appropriate string in the pool, and if it already exists, simply point the reference to it, and if not, create a new one.

When you create a in the previous example, an "ABC" is first created in the string pool, then a points to it, and when you create B, B points directly to it because "ABC" already exists.

formatting strings

The format () method of the string class is used to create a formatted string and to concatenate multiple string objects.

There are two overloaded forms of the Format () method:

    • Format (string format, Object ... args) a new string that uses the local locale to develop a string format and parameters to generate a new formatted string.
    • Format (locale locale, string format, Object ... args) uses the specified locale to develop string formatting and parameters to generate a formatted string.

Displays different conversion characters that implement different data types to string conversions:

Conversion character

Description

Example

%s

String type

"Mingrisoft"

%c

Character type

' m '

%b

Boolean type

True

%d

Integer type (decimal)

99

%x

Integer type (hex)

Ff

%o

Integer type (octal)

77

%f

Floating-point types

99.99

%a

Hexadecimal floating-point type

Ff.35ae

%e

Index type

9.38e+5

%g

Common floating-point types (shorter in type F and e)

%h

Hash code

%%

Percent type

%n

Line break

%tx

Date and Time type (x represents a different date and time conversion character



Test Case:

1  Public Static voidMain (string[] args) {2String str=NULL; 3Str=string.format ("hi,%s", "Wang Li"); 4 System.out.println (str); 5Str=string.format ("hi,%s:%s.%s", "Wang Nan", "Li Li", "Wang Zhang"); 6 System.out.println (str); 7System.out.printf ("Uppercase of the letter A is:%c%n", ' a '); 8System.out.printf ("3>7 The result is:%b%n", 3>7); 9System.out.printf ("Half of 100 is:%d%n", 100/2); TenSystem.out.printf ("100 of 16 binary number is:%x%n", 100);  OneSystem.out.printf ("100 of 8 binary numbers are:%o%n", 100);  ASystem.out.printf ("50 yuan book 8.5 discount is:%f Yuan%n", 50*0.85);  -System.out.printf ("16 of the price above is:%a%n", 50*0.85);  -System.out.printf ("Index of price above:%e%n", 50*0.85);  theSystem.out.printf ("The index of the above price and the length of the floating point result is shorter:%g%n", 50*0.85);  -System.out.printf ("The above discount is%d%%%n", 85);  -System.out.printf ("The hash code for the letter A is:%h%n", ' a ');  -}

Output Result:

  1  hi, Wang Li   2  hi, Wang Nan: Wang Li. King Zhang     3>7 Result: false   5 The half of  100 is:  6  100 of 16 decimal numbers are:  7  10 0 of 8 binary numbers are: 144  8  50 Yuan Book 8.5 discount is: 42.500000 meta " Span style= "color: #008080;" > 9  The 16 binary of the above price is: 0x1.54p5  10  The index of the above price indicates: 4.250000e+01 11  the exponent of the price above and the length of the floating-point result are shorter: 42.5000 12  The discount above is 85% 13  the hash code for the letter A is: $ 
String, StringBuffer, and Stringbuider

First, by reading the Java source code, we can find that the string class is a class that is final marked as not inheritable, and that it uses a char array to record the value of the entire string, and most of the methods of the string class that alter the data (such as SUBSTRING, Concat and replace, etc.), are directly created after a new string object is changed and returned, so we say that the data of string cannot be changed, and in fact Java has no way of changing its internal char array for string design.

Always remember one point here: " any change to a string object does not affect the original object, and any changes associated with it will generate a new object ."

Look at an example.
1  Public classMain {2          3 Public Static voidMain (string[] args) {4String str1 = "Hello World";5String str2 =NewString ("Hello World");6String str3 = "Hello World";7String STR4 =NewString ("Hello World");8          9System.out.println (str1==str2);TenSystem.out.println (str1==STR3); OneSystem.out.println (str2==STR4); A     } -}

The result of the output is:

1 false 2 true 3 false

Why do you have such a result? Let's explain why:

For the JVM memory mechanism, there is a part of the class file that stores the literal constants and symbolic references generated during compilation, called the class file constant pool, which corresponds to the run-time pool of the method area during the run.

So in the above code, string str1 = "Hello World"; and string str3 = "Hello World"; Both literal constants and symbolic references are generated during compilation, and the literal constant "Hello World" is stored in the run-time pool (of course only one copy) during the run. By binding a string object to a reference in this way, the JVM execution engine looks for the same literal constant in the run-time pool, and if it does, points the reference directly to the literal constant that already exists, or creates a space in the run-time pool to store the literal constant. and point the reference to the literal constant.

As is known to all, the generation of objects through the New keyword is done in the heap area, and the process of object generation in the heap is not to detect whether the object already exists. As a result, objects are created by using new, which must be different objects, even if the contents of the strings are the same.

StringBuilder

Let's take a look at the following example:

1  Public classMain {2 Public Static voidMain (string[] args) {3String string = "";4 for(inti=0;i<10000;i++){5string + = "Hello";6         }7     }8}

We know that each connection to a string is to regenerate a new string, and then this code runs to create 10,001 string objects, whereas there are only 1 string objects referenced, and other objects are garbage collected, resulting in memory and CPU waste.

In order to solve this situation, Java has designed a char array that stringbuilder,stringbuilder can directly modify its internal records, and does not generate extra objects when changing strings, as follows:

1  Public classMain {2  Public Static voidMain (string[] args) {3StringBuilder StringBuilder =NewStringBuilder ();4 for(inti=0;i<10000;i++){5Stringbuilder.append ("Hello");6         }7     }8}

The resulting result is consistent with the method above using string, but avoids the waste of memory and CPU resources.

StringBuffer

In fact StringBuffer provides the same functionality and StringBuilder, the only difference is that StringBuilder is thread insecure and can only be used in a single thread, and StringBuffer is threaded and can be used in multiple threads.

Java Learning Note (ii): String

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.