在Java中常量就是在程序运行过程中,其值不变的量。Java中是以关键字final来声明一个常量的。例如:
/*常量的使用*/
public class Constants
{
   public static void main(String[] args)
   {
     final double CM_PER = 3.14;
     double radius = 5;
     System.out.println("the circle area is " + CM_PER * radius * radius);
   }
}
输出结果:
                  the circle area is 78.5
        关键字final对变量进行一次赋值,它的值一量设定,就不再变化。习惯上常量名都用大写。
        声明常量的意义,常量的声明从某种程度上讲是保证了数据的惟一性。在程序的运行中有时为了需要一个常量在所有的代码中都代表同一个值,并且这个值是不允许改变的,我们通过声明这个变量为常量。如果想声明一个常量为类可用的,你可以把这个常量声明为类常量,类常量的声明使用关键字static final。例如:
/*类常量的使用*/
public class Constants2
{
   static final double CM_PER = 3.14;
   public static void main(String[] args)
   {
    double radius = 5;
    System.out.println("the circle area is " + CM_PER * radius * radius);
    }
}
输出结果:
                  the circle area is 78.5
        在定义类常量后,可以在类中任何一个方法中使用这个常量。
	
posted on 2007-05-09 14:59 
心随Wǒ动 阅读(345) 
评论(0)  编辑  收藏