第3部分java中的变量
3.1 变量的定义
*在程序运行中,能发生改变的量。
3.2 变量的类型
*整数型 byte short int long
*浮点数型 double float
*字符型 char
*布尔型 boolean
注意:long在赋值时数据值后要加L
float在赋值时数据值后加F
byte占用一个字节,数字大小为-2^7 — 2^7 -1
short占用两个字节,数字大小为-2^15 — 2^15-1
int占用四个字节,数字大小为-2^31 — 2^31-1
long占用八个字节,数字大小为-2^63 — 2^63-1
float占用四个字节,数字大小为1.4E-45~3.4E+38 , -1.4E-45~-3.4E+38 。
double占用八个字节,数字大小为4.9E-324~1.7E+308, -4.9E-324~-1.7E+308 。
char占两个字节,数字大小为0—2^16-1。
Boolean占一个字节,其取值只有两个,true和false。
赋值
格式1: 变量类型 标识符; 格式2: 变量类型 标识符=数据值;
标识符=数据值;
如 int x; int x=4; 将4赋值给x
x=4; 将4赋值给x
public class Example {
public static void main(String[] args){
int x=4;
System.out.println("x="+x);
}
}
public class exampleOne {
public static void main(String[] args){
char x='g';//只能存储单一字符
System.out.println(x);
}
}
3.3 类型转换
自动转换:2种类型在转换过程中,不需要声明。
条件:
*2种类型彼此兼容
*目标类型的取值范围大于源类型取值范围
//变量的自动转换
public class Example1 {
public static void main(String[] args){
byte b=4;
int x=b;
}
}
强制类型转换:2种类型在转换过程中,需要声明。
格式 目标类型 变量名=(目标类型)值;
特点
*2种类型彼此不兼容
*目标类型的取值范围小于源类型取值范围
public class Example2 {
public static void main(String[] args){
long x=4L;
int y=(int)x;
System.out.println(y);
}
}
3.4 变量的作用域
public class example3 {
public static void main(String[] args){
int x=12;{
int y=10;
System.out.println("x is"+x);
System.out.println("y is"+y);
}
x=y;
System.out.println("x is"+x);
}
}
该代码错误 因为给y赋值超出了它的作用域。
去掉 x=y; 代码正确



