final回顾:
1.修饰类 类不可被继承
2.修饰方法 方法不能被重载
3.修饰变量 变量引用不可变
4.需要程序员手动显示赋值
5.如果定义final变量时就为其进行初始化,则改变量在编译期间其值就已确定
实例1:
public class StringAndFinal
{
public static void main(String [] args){
StringAndFinal saf = new StringAndFinal();
System.out.println("action test1......");
saf.test1();
System.out.println("action test2......");
saf.test2();
}
public void test1(){
String s1 = "helloworld";
String s2 = "hello" + "world";
System.out.println("s1=s2? \t"+(s1 == s2));//true
String str1 = "hello";
String str2 = "world";
String s3 = str1 + str2;
System.out.println("s1=s3? \t"+(s1 == s3)); //false
}
public void test2(){
String s1 = "helloworld";
String s2 = "hello" + "world";
System.out.println("s1=s2? \t"+(s1 == s2));//true
final String str1 = "hello";
final String str2 = "world";
String s3 = str1 + str2;
System.out.println("s1=s3? \t"+(s1 == s3));//true
}
}
实例2:
public class FinalInitTest
{
final String str1;
final String str2;
final String str3 = "Java";
//not static block
{
str1 = "Java";
}
public FinalInitTest()
{
str2 = "Java";
}
public void display()
{
System.out.println(str1 + str1 == "JavaJava");//false
System.out.println(str2 + str2 == "JavaJava");//false
System.out.println(str3 + str3 == "JavaJava");//true
}
public static void main(String[] args) {
FinalInitTest fit = new FinalInitTest();
fit.display();
}
}