View RSS Feed

My Java Tips

Final variables

Rate this Entry
by , 11-06-2011 at 06:57 PM (900 Views)
A final variables in Java are can only be assigned once. Once they are assigned some value, they cannot be assigned some other value.

If you have final class variable, they must be assigned to in the constructor of the class. An interesting thing is that the value of a final variable is not necessarily known at compile time. Consider the following example:

Java Code:
public class Sphere {

    public static final double PI = 3.141592653589793;
    public final double radius;
    public final double xpos;
    public final double ypos;
    public final double zpos;

    Sphere(double x, double y, double z, double r) {
         radius = r;
         xpos = x;
         ypos = y;
         zpos = z;
We have 3 final variables in the example. The first one (PI) is static as well, which allows us to access it without initiating the class.

Submit "Final variables" to Facebook Submit "Final variables" to Digg Submit "Final variables" to Submit "Final variables" to StumbleUpon Submit "Final variables" to Google

Tags: None Add / Edit Tags
Java SE