Monday, November 25, 2019
Final Keywords)
Create a Java Constant Variable (Static/Final Keywords) A constant is aà variableà whose value cannot change once it has been assigned. Java doesnt have built-in support for constants, but the variable modifiersà static and final can be used to effectively create one. Constants can make your program more easily read and understood by others. In addition, a constant is cached by the JVM as well as your application, so using a constant can improve performance.à Static Modifier This allows a variable to be used without first creating an instance of the class; a static class member is associated with the class itself, rather than an object. All class instances share the same copy of the variable. This means that another application or main() can easily use it. For example, class myClass contains a static variable days_in_week: public class myClass { à static int days_in_week 7;} Because this variable is static, it can be used elsewhere without explicitly creating a myClass object: public class myOtherClass {à à static void main(String[] args) { à à à System.out.println(myClass.days_in_week); à } } Final Modifier The final modifier means that the variables value cannot change. Once the value is assigned, it cannot be reassigned.à Primitive data types (i.e., int, short, long, byte, char, float, double, boolean) can be made immutable/unchangeable using the final modifier. Together, these modifiers create a constant variable. static final int DAYS_IN_WEEK 7; Note that we declared DAYS_IN_WEEK in all capsà once we added the final modifier. Its a long-standing practice among Java programmers to define constant variables in all caps, as well as to separate words with underscores. Java doesnt require this formatting but it makes it easier for anyone reading the code to immediately identify a constant.à Potential Problems With Constant Variables The way the final keyword works in Java is that the variables pointer to the value cannot change. Lets repeat that:à its the pointer that cannot change the location to which its pointing. Theres no guarantee that the object being referenced will stay the same, only that the variable will always hold a reference to the same object. If the referenced object is mutable (i.e. has fields that can be changed), then the constant variable may contain a value other than what was originally assigned.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.