栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JavaSE String和StringBuffer

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JavaSE String和StringBuffer

String介绍

Java JDK中内置的一个类:java.lang.String

  1. String表示字符串类型,属于引用数据类型,不属于基本数据类型
  2. 在Java中随便使用双引号括起来的都是String对象。例如"abc"
  3. Java中规定,双引号括起来的字符串,是不可变的,也就是常说"abc"自出生到最终死亡,不可变
  4. 字符串都是直接存储在"方法区"中的"字符串常量池"当中,因为字符串在实际开发中使用太频繁,这样能够提高执行效率
String的存储原理   例1
public class StringTest01 {
    public static void main(String[] args) {

        //这两行代码表示底层创建了3个字符串对象,都在字符串常量池当中
        String s1 = "abcdef";
        String s2 = "abcdef"+"xy";

        //分析:这是使用new的方式创建的字符串对象.这个代码中的"xy"是从哪里来的
        //new对象的时候一定在堆内存当中开辟空间,s3保存的是对象的内存地址
        String s3 = new String("xy");
        //i变量中保存的是100这个值
        int i=100;

    }
}

 例2
public class User {
    private int id;
    private String name;

    public User() {

    }

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class UserTest {
    public static void main(String[] args) {

        User user = new User(110, "张三");
        
    }
}
 例3
public class StringTest02 {
    public static void main(String[] args) {
        String str1 = "hello";
        String str2 = "hello";
        System.out.println(str1==str2);
        System.out.println(str1.equals(str2));

        System.out.println("-----------");
        String x = new String("xyz");
        String y = new String("xyz");
        System.out.println(x==y);
        System.out.println(x.equals(y));
        System.out.println("xyz".equals(x));
    }
}

结果: 

 

 String常见的构造方法
  1. String s = " ";最常用
  2. String s = new String(" ");
  3. String s = new String(char数组);
  4. String s = new String(char数组,起始下标,长度);
  5. String s = new String(byte数组);
  6. String s = new String(byte数组,起始下标,长度);
 例子
public class StringTest03 {
    public static void main(String[] args) {

        //创建字符串对象最常见的方式
        String s1 = "Hello World!";
        String s2 = new String("Hello World!");

        //String(byte[] bytes)
        byte[] bytes = {97, 98, 99};//97是a,98是b,99是c
        String s3 = new String(bytes);
        System.out.println(s3);//输出一个引用的时候,会自动调用一个toString()方法

        //String(字节数组,数组元素下标的起始位置,长度)
        //将byte数组的一部分转换为字符串
        String s4 = new String(bytes, 1, 2);
        System.out.println(s4); //bc

        //将char数组全部转化为字符串
        char[] chars = {'我','是','中','国','人'};
        String s5 = new String(chars);
        System.out.println(s5);

        //将char的一部分转化为字符串
        String s6 = new String(chars,2,3);
        System.out.println(s6);
    }
}

 

 String类常用方法
  1. char charAt(int index):截取字符串中的一个字符
  2. int compareTo(String anotherString):字符串之间比较大小不能直接用> <,要用compareTo()方法,该方法是按字典顺序去比较的
  3. boolean contains(CharSequence s):判断前面的字符串中是否包含后面的子字符串
  4. boolean endsWith(String suffix):判断当前字符串是否以某个字符串结尾
  5. boolean equals(Object anObject):比较两个字符串必须使用equals方法,不能使用"=="
  6. boolean equalsIgnoreCase(String anotherString):判断两个字符串是否相等,并且同时忽略大小写
  7. byte[] getBytes():将字符串对象转换成字节数组
  8. int indexOf(String str):判断某个字符串在当前字符串第一次出现的索引
  9. int lastIndexOf(String str):判断某个字符串在当前字符串最后一次出现的索引
  10. boolean isEmpty():判断某个字符串是否为空字符串,底层源代码调用的应该是字符串的length()方法
  11. int length():判断字符串长度
  12. String replace(CharSequence target,CharSequence replacement):String的父接口就是CharSequence
  13. String[ ] split(String regex):拆分字符串 
  14. boolean startsWith(String prefix):判断某个字符串是否以某个字符串开始
  15. String substring(int beginIndex):截取字符串
  16. String substring(int beginIndex,int endIndex):起始索引(包括),结束索引(不包括)
  17. char[] toCharArray():将字符串转换为字符数组
  18. String toLowerCase():转换为小写
  19. String toUpperCase():转换为大写
  20. String trim():去除前后空格
  21. valueOf():String中唯一的静态方法
例1 方法测试
public class StringTest04 {
    public static void main(String[] args) {

        //1.char charAt(int index)
        char c = "中国人".charAt(1);
        System.out.println(c);// 国

        //2.int compareTo(String anotherString)
        int result1 = "abc".compareTo("abc");
        System.out.println(result1); // 0
        //拿字符串1的第一个字母和字符串2的第一个字母比较,能分胜负就不再笔记比较了
        int result2 = "abc".compareTo("def");
        System.out.println(result2); //1-4=-3
        //按字典顺序去比较
        int result3 = "xyz".compareTo("abc");
        System.out.println(result3); // 24-1=23

        //3.boolean contains(CharSequence s)
        System.out.println("HelloWorld".contains("World"));//true

        //4.boolean endsWith(String suffix)
        System.out.println("test.txt".endsWith(".java"));// false

        //5.boolean equals(Object anObject)
        //equals方法有没有调用compareTo方法?JDK13中并没有调用compareTo
        System.out.println("abc".equals("abc"));

        //6.boolean equalsIgnoreCase(String anotherString)
        System.out.println("abc".equalsIgnoreCase("ABC"));//true

        //7.byte[] getBytes()
        byte[] bytes = "abc".getBytes();
        for(int i=0;i 
例2 println源代码 
 eg:
    public void println(int x) {
        synchronized (this) {
            print(x);
            newline();
        }
    }

    public void print(int i) {
        write(String.valueOf(i));
    }
StringBuffer介绍

思考:我们在实际开发中,如果需要进行字符串的频繁拼接,会有什么问题?

因为Java中的字符串是不可变的,每一次拼接都会产生新字符串。这样会占用大量的方法区内存,造成内存空间的浪费。如果以后需要进行大量的字符串拼接操作,建议使用JDK中自带的:

  • java.lang.StringBuffer:底层实际上是byte[] 数组,往StringBuffer中放字符串,实际上是放到byte数组中了,初始化容量是16。在创建StringBuffer的时候尽可能给定一个初始化容量,最好减少底层数组的扩容次数,预估计一下,给一个大一些初始化容量
  • java.lang.StringBuilder:也能用于拼接,StringBuilder中的方法都没有synchronized关键字修饰,表示StringBuilder在多线程环境下运行是不安全的;StringBuffer中的方法则都有synchronized关键字修饰,表示StringBuffer在多线程环境下运行是安全的
例1 StringBuffer
public class StringBufferTest01 {
    public static void main(String[] args) {

        //创建一个初始化容量为16的byte[]数组(字符串缓冲区对象)
        StringBuffer stringBuffer = new StringBuffer();

        //拼接字符串,以后拼接字符串统一使用append()方法
        stringBuffer.append("a");
        stringBuffer.append(3.14);
        stringBuffer.append(true);
        //append方法底层在进行追加的时候,如果byte数组满了,会自动扩容
        stringBuffer.append(100L);
        System.out.println(stringBuffer); //a3.14true100

        StringBuffer sb = new StringBuffer(100);
    }
}
例2 StringBuilder
public class StringBuilderTest01 {
    public static void main(String[] args) {

        //使用StringBuilder也是可以完成字符串的拼接
        StringBuilder sb = new StringBuilder();
        sb.append(100);
        sb.append(true);
        sb.append("hello");
        sb.append(100L);
        System.out.println(sb); //100truehello100
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/344898.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号