一.final
final修饰变量:变量的地址不能被改变(不能被重新赋值)。
final修饰方法:该方法不能被重写。
final修饰类:该类不能被继承。
二.String为什么被设计为不可变的
String的源码:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
设计为不可变的有两点考虑:
- 设计(安全):String被final修饰,保证子类不会改变语义。String一旦创建后保存在字符串常量池中,以供共享,如果不设计为不可变,多个线程进行操作会出现安全问题。
- 效率:字符串常量池 大量频繁使用。
三:string的不可变体现
- 当对字符串重新赋值时,需要重新指定内存区域进行赋值,不能使用原value数组进行赋值。
- 当字符串进行拼接时,也需要重新指定内存区域进行赋值。
- 当调用String的replace方法修改指定字符串时,也需要重新指定内存区域进行赋值。
import org.junit.Test;
/**
* String的基本使用:体现String的不可变性
*/
public class StringTest1 {
@Test
public void test1() {
String s1 = "abc";
String s2 = "abc";
s1 = "hello";
System.out.println(s1 == s2);
System.out.println(s1);
System.out.println(s2);
}
// false
// hello
//abc
@Test
public void test2() {
String s1 = "abc";
String s2 = "abc";
s2 += "def";
System.out.println(s2);
System.out.println(s1);
}
//abcdef
// abc
@Test
public void test3() {
String s1 = "abc";
String s2 = s1.replace('