当前位置:
文档之家› Java课件第二章补充字符串
Java课件第二章补充字符串
8
Trace Code
String s = "Java"; s = "HTML";
After executing s=“java”;
s 0x1245
s:String
String object not be changed
After executing s=“HTML”;
Note:The parameter is a String object
5
Difference between new and shorthand initializer
String a= "abc"; String b= "abc"; Question: How many String objects are created?
One
6
Note
A new object is created if you use the new operator. If you use the string initializer, no new object is created if the interned object is already created.
improve efficiency and save memory Using String object’s intern method to return a canonical string
10
Canonical Strings
intern: public native String intern() Returns a canonical representation for the string object.
Chapter 2 The String Class
I Constructing a String II String Methods
1
The String Class
Constructing a String: Obtaining String length and Retrieving Individual Characters in a string String String Concatenation (concat) Substrings (substring(index), substring(start, end)) Comparisons (equals, compareTo) String Conversions Finding a Character or a Substring in a String Conversions between Strings and Arrays Converting Characters and Numeric Values to Strings
If s and t are strings such that s.equals(t), it is guaranteed that
s.intern() == t.intern().
11
Examples
String s = "Welcome to Java"; String s1 = new String("Welcome to Java"); String s2 = s1.intern(); String s3 = "Welcome to Java"; System.out.println("s1 == s is " + (s1 == s)); System.out.println("s2 == s is " + (s2 == s)); System.out.println("s == s3 is " + (s == s3));
3
Storage String pool & stack & heap
String pool(字符串池): JVM has a String pool, it saves a lot of String objects that created by shorthand initializer. Data sharing Stack (栈) : Store primitive data(char、byte、short、 int、long、float、double、boolean)and constructor. Data sharing. heap(堆):Store Object.
2
Constructing Strings
Format: String newString = new String(stringLiteral); String message = “stringLiteral";
Example: String message = new String(“Hello"); String message = "Welcome to Java";
4
Difference between new and shorthand initializer
String str=new String("abc");
Question: How many String objects are created? Two
Constructor: public String(String original) { //other code ... }
× s 0x1245
s:String String object for “HTML”
s:String String object for “Java”
9
Canonical Strings(规范字符串)
canonical string: if two String objects were created with the same string literal using the shorthand initializer, then the JVM stores them in the same object. This string literal is called canonical string.
7
Strings Are Immutable
A String object is immutable; its contents cannot be changed.
Does the following code change the contents of
the string?
String s = "Java"; s = "HTML";