常用类-String类
-
String 对象用于保存字符串,也就是一组字符序列
-
字符串常量对象是用双引号括起来的字符序列
-
字符串使用的是Unicode字符编码,一个字符占两个字节
-
常用构造器
String s1 = new String(); String s2 = new String(String original); String s3 = new String(char[] a); String s4 = new String(char[] a,int Startindex,int count); String s5 = new String (byte[] b);
-
接口Serialization [String 可以串行化 表示可以在网络上进行出传输]
-
接口comparable [String 对象可以比较大小]
-
String 是final 类,不能被其它类继承
-
String 有属性 private final char value [ ]; 用于存放字符串内容
-
一定要注意: value是一个final类型 不可以修改【value的地址不可修改】
-
解释:不可修改指的是 value不能指向新的对象 但可以修改单个字符的内容
final char[] value = {'a','b','c'}; // 这里指的是修改单个字符的内容 正确 value[0] = 'H'; char[] a2 = {'t','o'}; value = a2; // 报错
-
-
创建String 对象的两种方式
String s = "deel"; // 直接赋值 String s = new String("deel"); // 调用构造器
-
内存分析
-
测试题
-
解析:
-
equals 比较的是字符串的内容 ; “=” 比较的是地址
答案:true true
-
inter () 返回这个字符串池中与与之相同的字符串的 地址
答案:true false true false
-
答案:true true true false
-
String对象特性
-
String s1 = "hello"; s1 = "haha"; // 创建了两个对象
-
题目1
String a = "hello" + "abc"; // 创建了1个对象
解释: 编译器的自主优化,判断创建的常量池对象,是否有引用指向 String a = “hello” + “abc”; => String a = “helloabc”;
-
String a= "hello"; String b = "abc"; String c = a+b;
在jdk8之前 源码分析
重要规则 :String c = “ab”+“cd”;常量相加在池中, String c = a+b; 变量相加在堆中
-
String s1 = "happy"; String s2 = "java"; String s5 = "happyjava"; String s6 = (s1+s2).intern(); System.out.println(s5==s6); System.out.println(s5.equals(s6)); // true true // s6 指向池中的 “happyjava”
-
public class Text1{ String str = new String("happy"); final char[] ch = {'j','a','v','a'}; public void change(String str,char ch[]){ str ="java"; ch[0] ='b'; } public static void main(String[] args){ Text1 ex = new Text1(); ex.change(ex.str,ex.ch); System.out.println(ex.str +"and"); System.out.println(ex.ch); } } // happyandhava // 数值默认放入堆内
常用方法
-
注意点