Java 常量的使用。
创建一个 Contants.java 的文件,如下:
打印整型常量、小数常量、字符常量、字符串常量、布尔常量,输入以下代码:
public class Contants{
public static void main(String [] args){
System.out.println("嗨客网(www.haicoder.net)\n");
//1.整型常量
System.out.println(0);
System.out.println(1);
System.out.println(100);
//2.小数常量
System.out.println(0.1);
System.out.println(99.9);
//3.字符常量
System.out.println('h');
System.out.println('嗨');
System.out.println('2');
//4.字符串常量
System.out.println("www.haicoder.net");
System.out.println("嗨客网");
System.out.println("haicoder123");
//5.布尔常量
System.out.println(true);
System.out.println(false);
}
}
编译 Contants.java 程序,输入以下命令:
javac Contants.java
运行如下:
编译之后,我们再查看文件夹,发现多了一个 Contants.class 文件,此时证明,编译成功,如下:
最后我们运行程序,输入以下命令:
java Contants
运行如下:
此处,需要注意的一点,字符变量内容必须是一个内容,以下的情况会发生编译失败,如下:字符内容为空:
public class Contants{
public static void main(String [] args){
System.out.println("嗨客网(www.haicoder.net)\n");
//编译失败:字符常量为空
System.out.println('');
}
}
编译报错,如下:
字符内容为多个字符:
public class Contants{
public static void main(String [] args){
System.out.println("嗨客网(www.haicoder.net)\n");
//编译失败:字符常量为多个字符
System.out.println('haicoder');
}
}
编译报错,如下:
至此,我们发现 Java 是一个非常规范的语言,所有的语法必须符合规范,否则就会发生报错。