final modifier:
Final modified member variables must have an initial value explicitly specified by the programmer.
Field of a class: The initial value must be specified in a static initialization block or when declaring the Field.
Instance Field: The Field must be declared in a non-static initialization block or the initial value must be specified in the constructor.
final local variables: must be explicitly initialized by the programmer.
What is the difference between final modified basic variables and reference type variables?
Basic variables modified by final: Basic variables cannot be reassigned.
Final modified reference variable: It is only guaranteed that the address referenced by this reference type will not change, that is, it always refers to the same object, but this object can completely change.
Copy the code code as follows:
/**
*/
import java.util.*;
public class Demo5
{
public static void main(String[] args)
{
final B b = new B(22);
b.test();
// Legally change the value, but still point to the same reference
b.setAge(20);
System.out.println(b.getAge());
// illegal
// b = null;
b.test2();
}
}
/**
fianl modifies member variables
*/
class A
{
//legitimate
final int a = 10;
//Specify initial value in constructor or initialization block
final String str;
final int c;
final static double d;
{
str = "hello";
//illegal
// a = 100;
}
static
{
d = 100;
}
// The constructor can specify initial values for Fields not specified in the initialization block
publicA()
{
// illegal
// str = "ddd";
c = 1000;
}
public double changFinal()
{
// You cannot specify an initial value for final in a normal method
// return d = 1000.90;
return 0;
}
}
/**
fianl modifies array objects
*/
class B
{
private int age;
publicB()
{
}
public B(int age)
{
this.age = age;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return this.age;
}
public void test()
{
final int[] arr={23,434,56,898};
System.out.println(Arrays.toString(arr));
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
arr[2] = 200;
System.out.println(Arrays.toString(arr));
//The following reassignment of Arr is illegal
// arr = null;
}
/**
Deepen your understanding of final
*/
public void test2()
{
String str1 = "Better future";
//Direct reference to "Better Future" in the constant pool
String str2 = "Beautiful"+"Future";
//true
System.out.println(str1 == str2);
String s1 = "Beautiful";
String s2 = "Future";
String s3 = s1+s2;
//false s1 s2 is just a variable that cannot be determined at compile time
//If you want to determine it at compile time, use final to modify s1 s2
System.out.println(str1 == s3);
}
}
Do you guys know something about the final modifier in Java? I believe it has been explained clearly in the comments, so I won’t go into details here.