final note

Everyone knows that final is one of the modifiers in java.
Used to decorate classes, methods or variables.
This article does not discuss the above usage, at least what is discussed, please see the following code:
public class Main{
	static void normalAdd(){
		byte b1=1,b2=1,b3;
// b3=b1+b2;//Writing like this will cause the compilation to fail, because b1+b2 will be automatically upgraded to int type, and int must be forced to be assigned to byte
		b3=(byte) (b1+b2);//This is correct
	}
	static void finalAdd(){
		final byte b1=1,b2=1,b3;
		b3=b1+b2;//Look, nothing goes wrong here. Since both b1 and b2 are final, the data types are not promoted.
	}
	static void finalAdd2(){
		final byte b1=127,b2=1,b3;
// b3=b1+b2;//Writing like this will still cause the compilation to fail. Although b1 and b2 are both final types, the sum of the two numbers is 128, which is beyond the range of bytes.
		b3=(byte) (b1+b2);//So it still has to be forced here.
	}
}

Conclusion: Variables modified by fianl will not automatically change the type (special consideration for out-of-bounds cases)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326993940&siteId=291194637