一、常量
1.常量:
在程序运行中,值不发生改变的量
2.常量的分类:
java中的常量共分为6类
(1)字符串常量
用双引号括起来的内容,例如“hello,world"
(2)字符常量
用单引号括起来的常量
(3)整数常量
不带小数的数字
(4)小数常量
带小数的数字
(5)布尔常量
布尔值,表示真假。只有true,false
(6)空常量
一个特殊的值,空常量。值是:null
注意:空常量是不能直接输出的
public class ConstantWord{
public static void main(String[]args){
//字符串
System.out.println("hello");
// 数字
System.out.println(666);
// 字符
System.out.println('A');
//布尔
System.out.println(true);
//空常量:是不能直接输出的
//System.out.println(null);
}
}
二、变量
1.变量的概念
变量就是在程序运行过程中,其值可以发生改变的量。
可以实现修改一变量名直接批量修改变量对应的值的效果,起到牵一发而动全身的效果。
本质上:变量是存储在内存中的一小块区域。
2.变量定义:
变量名+数据类型+变量值
int a = 10
3.变量使用:
取值和修改值
取值: a
修改值: a = 20;
【.举例】
public class VariableDemo{
public static void main(String[]args){
//定义变量
int a = 10;
//输出变量
System.out.println(a);
//修改变量
a = 20;
System.out.println(a);
}
}
4.变量使用的4个注意事项
(1)在main方法中,定义的变量名不能重复
(2)定义变量的时候需要给初始值,未赋值不能使用。
(3)定义long类型需要在初始值后面添加L。(否则机器会认为是int类型);
(4)定义float类型需要在初始值后面添加F。(浮点数默认值为double类型);
public class VariableDemo2 {
public static void main(String [] args){
//定义byte类型的变量b
byte b = 10;
System.out.println(b);
//定义short类型的变量s
short s = 100;
System.out.println(s);
//定义int类型的变量
int i = 1000;
System.out.println(i);
//定义double类型的变量
double d = 13.24;
System.out.println(d);
//定义char类型的变量
char c = 'a';
System.out.println(c);
//定义boolean类型的变量
//下列语句报错,因为变量b在上面的代码中已经定义过
//boolean b = true;
//System.out.println(b);
boolean bb = true;
System.out.println(bb);
//定义long类型的变量
//下列语句报错:未初始化变量(未给变量赋初始值)
//long l;
//System.out.println(l);
long l = 100000000L;
System.out.println(l);
//float类型后面需要添加F
float f = 3.14f;
System.out.println(f);