javaSE基础第二章(变量与运算符)
目录
1 关键字和保留字
2 标识符
3 变量
基本数据类型转换
/*
基本数据类型之间的运算规则:
前提:这里讨论只是7种基本数据类型变量间的运算。不包含boolean类型的。
1. 自动类型提升:
结论:当容量小的数据类型的变量与容量大的数据类型的变量做运算时,结果自动提升为容量大的数据类型。
byte 、char 、short --> int --> long --> float --> double
特别的:当byte、char、short三种类型的变量做运算时,结果为int型
2. 强制类型转换:见VariableTest3.java
说明:此时的容量大小指的是,表示数的范围的大和小。比如: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);//123.0
//***************特别地*********************
char c1 = 'a';//97
int i3 = 10;
int i4 = c1 + i3;
System.out.println(i4);
short s2 = 10;
//char c2 = c1 + s2;//编译不通过
byte b2 = 10;
//char c3 = c1 + b2;//编译不通过
//short s3 = b2 + s2;//编译不通过
//short s4 = b1 + b2;//编译不通过
//****************************************
}
}
/*
String类型变量的使用
1. String属于引用数据类型,翻译为:字符串
2. 声明String类型变量时,使用一对""
3. String可以和8种基本数据类型变量做运算,且运算只能是连接运算:+
4. 运算的结果仍然是String类型
*/
class StringTest {
public static void main(String[] args) {
String s1 = "Hello World!";
System.out.println(s1);
String s2 = "a";
String s3 = "b";
//char c = '';//编译不通过
//***********************
int number = 1001;
String numberStr = "学号:";
String info = numberStr + number;// +:连接运算
boolean b1 = true;
String info1 = info + b1;// +:连接运算
System.out.println(info1);
//***********************
//练习1
char c = 'a';//97 A:65
int num = 10;
String str = "hello";
System.out.println(c + num + str);//107hello
System.out.println(c + str + num);//ahello10
System.out.println(c + (num + str));//a10hello
System.out.println((c + num) + str);//107hello
System.out.println(str + num + c);//hello10a
//练习2
//* *
System.out.println("* *");
System.out.println('*' + '\t' + '*');
System.out.println('*' + "\t" + '*');
System.out.println('*' + '\t' + "*");
System.out.println('*' + ('\t' + "*"));
//***********************
//String str1 = 123;//编译不通过
String str1 = 123 + "";
System.out.println(str1);//"123"
//int num1 = str1;
//int num1 = (int)str1;//"123"
int num1 = Integer.parseInt(str1);
System.out.println(num1);//123
}
}
class VariableTest4 {
public static void main(String[] args) {
//1.编码情况1:
long l = 123213;
System.out.println(l);
//编译失败:过大的整数
//long l1 = 21332423235234123;
long l1 = 21332423235234123L;
//****************
//编译失败
//float f1 = 12.3;
float f1 = (float)12.3;
//2.编码情况2:
//整型常量,默认类型为int型
//浮点型常量,默认类型为double型
byte b = 12;
//byte b1 = b + 1;//编译失败
//float f1 = b + 12.3;//编译失败
}
}
整型常量,默认类型为int型
浮点型常量,默认类型为double型