Constants in Java Why and How Copyright © 2005-2011 Curt Hill
Introduction There are two kinds of constants in Java Literals Named constants We will see the whys and wherefores now Copyright © 2005-2011 Curt Hill
Literal constants We have seen the following fours kinds of constants: -45 (int) 2.3 (floating point of type double) 1E4 (float) ‘A’ (char) “Hi” (string) Normally, merely inspecting the constant will tell you its type, as well as its value Copyright © 2005-2011 Curt Hill
Literals Continued What do we do to set the constant to something other than a standard int or double? We can use a suffix to tell it the type The L or l indicates that it is long The U or u indicates unsigned Floating point constants are by default double Suffix of F or f makes it a float, L a long double You may also use binary, octal or hexadecimal constants but we do not need to do that here Copyright © 2005-2011 Curt Hill
Literal Problems However, literal constants have the following problems that sometimes need to be dealt with We have to retype them each time This is a problem with high precision constants like PI Opportunities for typing errors Just remembering what the 14 digit value is We have to remember what they represent Small integer constants tend to get confused with one another Copyright © 2005-2011 Curt Hill
Example: Suppose that I am a manager and I have 5 people who work 5 days a week and 8 hours a day Thus the number of manhours is: workhours = 5 * 5 * 8; Now we will try something new, four ten hour days per week I use my text editor and change all 5s to 4s and all 8s to 10s We now get workhours = 4 * 4 * 10; The problem with the above expression is that the 5 and 8 have no inherent meaning Copyright © 2005-2011 Curt Hill
Alternative It would be better to say: int people = 5, dayperweek = 5, hoursperday = 8; ... workhours = people * dayperweek * hoursperday; Unfortunately that leads to a problem: An inadvertent assignment to one of the variables The solution is that we would like to be able to name constants, just like we name variables but without possibility of assignment Copyright © 2005-2011 Curt Hill
Final Keyword A feature that allows constants in Java is the final qualifier: final float pi = 3.14159; Any attempt to assign to this will result in an error The float type determines the precision used Copyright © 2005-2011 Curt Hill
Discussion The final is a keyword that prefixes the declaration This may be used anywhere a variable may be declared The declaration must have an initialization Copyright © 2005-2011 Curt Hill
Conclusion The reserved word final makes a variable into a constant Use to make the code more readable Shortens the typing for constants with many digits Prevents using global replaces from doing too much Copyright © 2005-2011 Curt Hill