程序中使用较多是字面常量,字面常量是在程序中表示的直接数据,比如:3.14、0、100,“pbteach.com”等。
例子:
/**
* 字面常量测试
* @author 攀博课堂(www.pbteach.com)
*
*/
public class ConstantDemo1 {
public static void main(String[] args) throws InterruptedException {
//输出一个整数
System.out.println(100);
//输出一个小数
System.out.println(3.14);
//输出一个字符串
System.out.println("www.pbteach.com");
}
}
常量使用final关键字来定义,其语法如下:
final 数据类型 常量名称 = 常量值;
final常量是在变量定义的基础上加final,表示该常量一旦赋值不可修改。
例子
/**
* 常量定义 测试
* @author 攀博课堂(www.pbteach.com)
*
*/
public class ConstantDemo2 {
//定义一个类常量,其它类也可以访问,访问方式是类名点常量名
public static final int classConstant = 1000;
public static void main(String[] args) throws InterruptedException {
//定义常量
final int a = 99;
System.out.println(a);
//下边报错,常量只能被赋值一次
//a=100;
//可以在定义时不赋值
final int b;
//一旦赋值不可更改
b=100;
//下边报错
// b=101;
System.out.println(b);
}
}
在main方法内部的常量只能在main中使用,main方法外部使用static final 关键字定义的叫做类常量,类常量的好处是其它类可以使用它的值,访问方式如下:
类名.常量名
例子:
在另外一个类的main方法中访问其它类的类常量,代码如下:
/**
* 常量定义 测试
* @author 攀博课堂(www.pbteach.com)
*
*/
public class ConstantDemo3 {
public static void main(String[] args) throws InterruptedException {
//访问ConstantDemo2中的类常量
System.out.println(ConstantDemo2.classConstant);
}
}