2.2常用类- String类

常用类-String类

  • 基本知识点 :
  1. String 对象用于保存字符串,也就是一组字符序列

  2. 字符串常量对象是用双引号括起来的字符序列

  3. 字符串使用的是Unicode字符编码,一个字符占两个字节

  4. 常用构造器

    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);
    
  5. 接口Serialization [String 可以串行化 表示可以在网络上进行出传输]

  6. 接口comparable [String 对象可以比较大小]

  7. String 是final 类,不能被其它类继承

  8. String 有属性 private final char value [ ]; 用于存放字符串内容

  9. 一定要注意: value是一个final类型 不可以修改【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"); // 调用构造器
    
  • 内存分析

  • 测试题

  • 解析:

    1. equals 比较的是字符串的内容 ; “=” 比较的是地址

      答案:true true

    2. inter () 返回这个字符串池中与与之相同的字符串的 地址

      答案:true false true false

    3. 答案:true true true false


String对象特性

  1. String s1 = "hello";
    s1 = "haha";
    // 创建了两个对象
    
  2. 题目1

    String a = "hello" + "abc";
    // 创建了1个对象
    

    解释: 编译器的自主优化,判断创建的常量池对象,是否有引用指向 String a = “hello” + “abc”; => String a = “helloabc”;

  3. String a= "hello";
    String b = "abc";
    String c = a+b;
    
    在jdk8之前 源码分析

    重要规则 :String c = “ab”+“cd”;常量相加在池中, String c = a+b; 变量相加在堆中

  4. 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”
    
  5. 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
    // 数值默认放入堆内
    

常用方法

  • 注意点

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值