==String
1. using help file
2. two ways to create a String object, using another String object or using "afad "
a) String str1 = "Hello"; ==> ".." is anonymous String object, so it can use String method
b) String str2 = new String("Hello");
method a) has "Hello" on help and str1 points to it
method b) has "Hello" on heap, then creates a new String object and copy "Hello" to it, then assign the new String object to str2. After copying, the "Hello" will be deleted later on by garbage collector
So method a) is much efficient
3. comparison
str1 != str2 because they are references
str1.equals(str2) compares the contents
String str3 = "Hello";
str1 == str3 because the compiler uses same copy of "Hello"
4. string content can not be changed, but the string reference can change
String str = "Hello";
str += "World";
"Hello" is in heap location a; "World" is in heap location b,
Step 1: str <= location a
Step 2: create a new String Object which has "Hello World" after copying at location c
Step 3: str <= location c
Step 4: strings at lcoation a and location b are deleted later on
So System.out.println(str) outputs "Hello World"
So it is very efficient especially used in a loop;
5. utility methods
5.1 String to char array:char[] toCharArray()
5.2 char array to String: String(char[] c), String(char[] c, int start, int num)
5.3 String to char: char charAt(int i)
5.4 String to byte array: byte b[] getBytes();
5.5 byte array to String: String(byte[] b), String(byte[] b, int start, int num)
5.6 check is starts by a String: boolean startsWith(String s);
5.7 check is ends by a String : boolean endsWith(String s);
5.8 replace all substring by another one: String replaceAll(String subs, String by);
5.9 get a substring: String substring(int beg), String substring(int beg, int end);
5.10 split string by another string: String[] split(String deliminator);
5.11 find a substring: int indexOf(String subs), boolean contains(String subs), int indexOf(String subs, int startindex)
5.12 get length: int length()
5.13 trim the blanks at beg and end: String trim();
5.14 change case: toUpperCase(), to toLowerCase()
没有评论:
发表评论