JAVA基础课程(第十七天)

第十七天 String

String特性

(1)代表字符串,

(2)String是一个final类,代表不可变的字符序列,不能被继承的(不可变性)

​ 不管怎么操作String,都需要重新定义内存区域进行赋值

(3)String 实现了Serializable表示可序列号,Comparable接口表示可以比较

(4)String对象的字符内容是存储咋一个字符数组value[] 中

(5)字符串常量池不会存相同内容的字符串

(6)String 部分源码如下

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;
    }

(7)内存说明图

在这里插入图片描述

(8)String创建的几种方式

		String s = "hello";

		String s1 = new String();

		String s2 = new String("hello");

		char[] ch = new char[]{'h','l'};
		String s3 = new String(ch);

		String s4 = new String(ch,0,1);

(9)特别说明

		String s1 = "hello";
		String s2 = "word";
		String s3 = "helloword";
		String s4 = "hello" + "word";
		String s5 = s1 + "word";
		String s6 = s1 + s2;
		String s7 = s6.intern();

		System.out.println(s3 == s4);  //true
		System.out.println(s3 == s5);  //false
		System.out.println(s3 == s6);  //false
		System.out.println(s3 == s7);  //true

​ ①常量与常量的拼接,结果在常量池,且常量池不会有相同内容的常量

​ ②只要其中有一个变量,结果就在对中

​ ③如果拼接的结果调用intern()方法,返回的结果就在常量池中

String常用方法

常用方法很多,需要String源码,理解其底层

/**
 *     public int length() {
 *         return value.length;
 *     }
 */
s1.length();//返回字符串的长度
/***
 *     public char charAt(int index) {
 *         if ((index < 0) || (index >= value.length)) {
 *             throw new StringIndexOutOfBoundsException(index);
 *         }
 *         return value[index];
 *     }
 */
s1.charAt(0);//返回某索引的字符
/**
 *     public boolean isEmpty() {
 *         return value.length == 0;
 *     }
 */
s1.isEmpty();//判断释放是空

s1.toUpperCase();//将所有的字符转成大写

s1.toLowerCase();//将所有的字符转成小写
String与char[]相互转换
		//String 转char[]
		
		String s1 = "hello";
		char[] c = s1.toCharArray();
		
		//char[]转String
		String s2 = new String(c);
String 与byte[]相互转换
//String 转byte[]

		String s1 = "hello";
		//默认设置字符集
		byte[] c = s1.getBytes();


		//byte[]转String
		String s2 = new String(c);


		/**
		 * 转成固定字符集
		 */
		try {
			//String 转byte[]
			byte[] c1 = s1.getBytes("gbk");
			//byte[]转String
			String s3 = new String(c1,"gbk");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
StringBuffer与StringBuilder

两者都继承AbstractStringBuilder,在AbstractStringBuilder可以看到底层存储依然是char[],但是没有被final修饰,所有都是可变的字符。

StringBuffer线程安全的,看源码可以看到方法都用synchronized修饰

StringBuffer线程不安全的,但是效率高

String 不可变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值