Java基本语法:变量的分类
一、数据类型
1、基本数据类型(primitive type):
数值型(整数类型(byte,short,int,long)、浮点类型(float,double))
字符型(char)
布尔型(boolean)
2、引用数据类型(reference type)
类(class) <----------------- 字符串在这里
接口(interface)
数组([array])
注:byte(1字节=8bit位) short (2字节) int (4字节) long(8字节)
byte范围:-128~127
float(4字节) double(8字节)
二、变量在类中声明的位置:
成员变量 vs 局部变量
class VariableTest1{
public static void main(String[] args){
byte b1 =12;
short s1 = 128;
int i1 = 1234;
//声明long型变量,必须以“l”或“L”结尾
//通常,定义整型变量时,使用int型
long l1 = 3434231L;
double d1 = 32.3;
// 定义float类型变量时,变量要以“f”或“F”结尾
float f1 = 12.3F;
System.out.println(f1)
//定义char型变量,通常使用一对''
char c1 = 'a';
//布尔型:boolean,只能取两个值之一:true \ false
//与c语言不一样,c语言一般用0或1表示,常在条件判断,循环条件中使用
boolean bbl = ture;
}
自动类型提升运算:
前提:讨论7种基本数据类型变量间得到运算,不包含boolean类型。
1、自动类型提升
当容量小的数据类型的变量与容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型
byte–> short–>int–>long–>float–>double
特别的:当byte、char、short三种类型的变量做运算时,结果为int型
2、强制类型转换 (自动类型提升运算的逆运算)
1、需要使用强转符:()
2、注意点:强制类型转换可能导致精度损失
说明:此时的容量大小指的是,表示数的范围的大和小。比如:float容量要大于long的容量
class VariableTest2{
public static void main(String[] args){
byte b1 = 2;
int i1 = 129;
//编译不通过
//byte b2 = b1 + i1;
int i2 = b1 + i1;
long l1 = b1 + i1;
System.out.println(i2);
float f = b1 + i1;
System.out.println(f);
short s1 = 123;
double d1 = s1;
System.out.println(d1);
char c1 = 'a';//97
int i3 = 10;
int i4 = c1 + i3;
System.out.println(i4);//107
class VariableTest3{
public static void main(String[] args){
double d1 = 12.3;
int i1 = (int)d1; //截断操作
System.out.println(i1); //12
//没有精度损失
long l1 =123;
short s2 = (short)l1;
//精度损失
int i2 = 128;
byte b = (byte)i2;
System.out.println(b);//-128
}
}
}
String类型的使用
1、string属于引用数据类型,翻译为:字符串
2、声明String类型变量时,使用一对“ ”
3、string可以和八种基本数据类型变量做运算,且运算只能是连接运算:+
4、运算的结果任然是String类型
class StringTest{
public static void main(string[] args){
String s1 = "Hello World";
String s2 = "a";
String s3 = " ";
Systemm.out.println(s1);
//char c = ''; //编译不通过
int number = 1001;
String numberStr = "学号";
String info = numberStr + number; // + (连接运算)
System.out.println(info); //学号: 1001
}
}