1、概述
- 字面量:是指在Java程序运行期间固定不变的数据。
2、分类
类型 含义 数据举例 整数常量 所有的整数 0,1,567,-9 小数常量
(浮点数常量)
所有的小数 0.0,-0.1,2.55 字符常量 单引号引起来,只能写一个字符,必须有内容 'a'、' '、'好' 字符串常量 双引号引起来,可以写多个字符,也可以不写 "A"、"Hello"、"你好"、"" 布尔常量 只有两个值(流程控制) true、false 空常量 只有一个值 null
- 两个单引号中间必须有且仅有一个字符,没有不行。
- 两个单引号中间必须有且仅有一个字符,有两个不行。
- 空常量不能直接用来打印输出。
package constant; public class Demo01Const { public static void main(String[] args) { System.out.println("ABC"); System.out.println("中"); System.out.println(""); System.out.println(" "); System.out.println("XYZ"); System.out.println("==============="); System.out.println(30); System.out.println(-500); System.out.println("==============="); System.out.println(3.14); System.out.println(-2.5); System.out.println("==============="); System.out.println('A'); System.out.println('\t'); System.out.println('6'); System.out.println(' '); System.out.println('中'); System.out.println('\n'); System.out.println('国'); System.out.println("==============="); System.out.println(true); System.out.println(false); } } D:\Java\jdk-17\bin\java.exe "-javaagent:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar=2815:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\bin" -Dfile.encoding=UTF-8 -classpath F:\IdeaProjects\JavaSenior\out\production\jdk8;D:\develop\maven\repository\junit\junit\4.13.1\junit-4.13.1.jar;D:\develop\maven\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar constant.Demo01Const ABC 中 XYZ =============== 30 -500 =============== 3.14 -2.5 =============== A 6 中 国 =============== true false Process finished with exit code 0
3、字面量
- 计算机是用来处理数据的,字面量就是告诉程序员:数据在程序中的书写格式。
3.1、字面量这个知识是告诉同学们什么啊?
- 数据在程序中的书写格式。
3.2、字符、字符串在程序中的书写格式有什么要求?
- 字符必须单引号围起来,有且仅有一个字符。
- 字符串必须用双引号围起来
3.3、几个常见的特殊值的书写格式是?
- true、false、null、\n、\t
3.4、扩展点:特殊字符
- \t 制表符 (在打印的时候,把前面字符串的长度补齐到8,或者8的整数倍。最少补1个空格,最多补8个空格。)
Microsoft Windows [版本 10.0.19042.985] (c) Microsoft Corporation。保留所有权利。 D:\javacode\chapter01>javac Test.java D:\javacode\chapter01>java Test name age tom 23 D:\javacode\chapter01>
- cmd命令行符合上述规律,IDEA不符合上述规律
package constant; public class ValueDemo2 { public static void main(String[] args) { System.out.println("name" + '\t' + "age"); System.out.println("tom" + '\t' + "23"); } } D:\Java\jdk-17\bin\java.exe "-javaagent:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\lib\idea_rt.jar=3897:D:\BaiduNetdiskDownload\IntelliJ IDEA 2023.2\bin" -Dfile.encoding=UTF-8 -classpath F:\IdeaProjects\JavaSenior\out\production\jdk8;D:\develop\maven\repository\junit\junit\4.13.1\junit-4.13.1.jar;D:\develop\maven\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar constant.ValueDemo2 name age tom 23 Process finished with exit code 0