package day2;
public class demo1 {
/*
基本数据类型之间的转换
byte short int long
float double
char 虽然是字符,其实是Unicode编码中的一个十进制整数,可以当成整数对待
boolean(不能和其他七种类型转换) true false
转换规则:
容量小的转容量大的
byte 1字节 127 转到short 2字节 可以
容量大的转容量小的
int 4字节 129 byte 1字节
float 4字节,但由于小数的二进制存储与整数二进制存储结构不同,
4字节的float大于4字节的int,大于8字节的long
byte-->short-->char-->int-->long-->float-->double
*/
public static void main(String[] args) {
//容量小的转容量大的 可以直接转换
byte a = 127;
int b = a;
long c = b;
float d = c;
//容量大的转容量小的 强制转换
//大转小,出现溢出
int m = 256;
byte n = (byte) m;//int --> byte 编译器无法通过,需要强制转换
System.out.println(n);//最后运行结果是0(可以多换几个数字操作)
float x = 10.5f;
//大转小,精度损失
long y = (long) x;//强制转换
System.out.println(y);
char z = 'a';
int zc = z;//97 char也可以参与转换
byte aa = 10;
byte bb = 10;
byte cc = (byte) (aa + bb);//byte short char在混合运算时都上升(!!!)为int类型
float dd = x + m + a;//混合运算,小类型默认都会转为最大的类型
double ee = x + m + a + 5.5;//混合运算,小类型默认都会转为最大的类型
}
}
运算符
1.关系运算符
package day2;
public class demo3 {
/*
关系(比较)运算符:> < <= >= == != 都是用于char类型之间去比较大小
== != 也可以适用于引用类型之间的比较
*/
public static void main(String[] args) {
int a = 10;
int b = 5;
char c = 'a';
/*
System.out.println(a>b);
System.out.println(a<b);
System.out.println(a>c);
System.out.println(a<c);
*/
String s1 = "abc";
String s2 = "abc";
System.out.println(s1==s2);
System.out.println(s1!=s2);
/*
int xx = 14;
int oo = 1;
System.out.println(xx>oo);
*/
}
}
2.算术运算符
package day2;
public class demo2 {
/*
算术运算符:
+ 加法运算 数值+数值(char)
字符串连接 数值+字符串 字符串+字符串 ==字符串
- 数值-数值
* 数值*数值
/ 数值/数值
%
++
--
*/
public static void main(String[] args) {
int a = 10;
int b = 5;
char c = 'a';
String d = "a";
System.out.println(a+b);//15
System.out.println(a+c);//105
System.out.println(a+d);//10a
//System.out.println(a%d);不支持
int m = 5;
m++;
++m;
System.out.println(m);//7*/
}
}
3.赋值运算符
package day2;
public class demo4 {
/*
赋值运算符 =. +=. -=. *= /= %=
*/
public static void main(String[] args) {
//int a = 10.5; 会报错! =把右边10赋给左边的变量,赋值时注意值的类型与声明的数据类型要匹配
int a = 10;
System.out.println(a+=5);//a = a+5
//举例eg(面试题)
short s = 3;
s += 2;//s =(byte)(s+2) +=可以隐式的进行数据类型的强制转换
//s = s+2;//会报错!s是short类型,3是int类型,无法赋值-->int类型,类型不匹配
}
}
4.条件运算符
public class demo6 {
/*
条件运算符(三元运算符或者三目运算符)
(条件表达式)?表达式1 : 表达式2
先执行条件表达式,
当条件表达式值为true时,运行表达式1
当为false时,运行表达式2
最终表达式1与表达式2必须返回一个结果
if(true){
}else{
}
*/
public static void main(String[] args) {
int score = 80;
String result = (score >=60)?"及格":"不及格";
System.out.println(result);
Math.max(10,3);
}
}