String string type uses detailed entry.
- String class represents string type, all text strings (e.g. "abc") Java programs are implemented as instances of this class. In other words, Java programs in all double-quoted strings, is an object of the String class.
- String Class In java.lang package, so when used need not guide the package.
Features of the String class
String String class definition also called immutable string.
- Immutable strings, their value can not be changed after creation, we find that the string change actually points to a new string object (before the string will be automatically recovered)
- It is because the value of the string object is immutable, they can be shared
- Corresponds to the array of characters (char []) on the effect of the string, but the underlying principle is the array of bytes (byte [])
Other ways to create a string object description
-
public String () to create a blank string object does not contain any content
-
public String (char [] chs) based on the contents of an array of characters, to create a string object
可以吧字符数组的类容转变成字符串 char[] chs = {'a','b','我','中','国'}; String rs = new String(chs); System.out.println(rs);//ab我中国
-
public String (byte [] bys) according to the content byte array to create a string object
byte[] bytes = {97 , 98 , 99 , 65 , 66 , 67}; String rs1 = new String(bytes); System.out.println(rs1);//abcABC
-
String s = "abc"; create a direct assignments of the String object, content is the classic abc written.!
note:
-
Direct definition of "string content" on the string constant pool.
-
out of the new objects in the heap memory string.
34 String name1 = "赵丽颖"; // 这里有创建对象的,对象放在常量池! 35 String name2 = "赵丽颖"; // 这里没有创建对象,共享了34行的字符串常量。 所以这里只创建了一个字符串对象 String name3 = new String("赵丽颖"); // 这里创建的字符串对象会放到堆内存中一份!常量池中也有一份! String name4 = "赵丽颖" ; // 对象在常量池中!所以没有重新创建对象! 所以这里也只创建了一个字符串对象
public class StringDemo {
public static void main(String[] args) {
// 1.String类型定义一个字符串对象变量:name
String name = "cx";
name += "学生" ; // name = name + "老师"
System.out.println(name); // cx学生
String name1 = "赵丽颖"; // 这里有创建对象的,对象放在常量池!
String name2 = "赵丽颖"; // 这里没有,共享了34行的字符串常量。
System.out.println(name1 == name2); // name1和name2指向的是同一个地址!!
// 1.创建字符串对象的其他方式:调用有参数构造器。
String name3 = new String("赵丽颖"); // 这里创建的字符串对象会放到堆内存中一份!!
String name4 = "赵丽颖" ; // 对象在常量池中!建议这样定义!
System.out.println(name3);
System.out.println(name4);
// 2. public String(char[] chs) 根据字符数组的内容,来创建字符串对象(了解)
char[] chs = {'a','b','我','中','国'};
String rs = new String(chs);
System.out.println(rs);
// 3.public String(byte[] bys) 根据字节数组的内容,来创建字符串对象
byte[] bytes = {97 , 98 , 99 , 65 , 66 , 67};
String rs1 = new String(bytes);
System.out.println(rs1);
}
}