①
byte data = (byte)300
这段代码输出data为44.
因为300被强转成byte型,300十六进制为13C
byte型保留3C,即十进制的44.
②
再看这段代码的输出:
int a=1;
System.out.printf("%d%n", a);
boolean b = true || (a++) == 1;
System.out.printf("%d%n", a);//1
boolean c = true | (a++) == 1;
System.out.printf("%d%n", a);//2
可以看出| 和||的区别:
|| 短路非 如果有条件True剩余条件不判断
| 如果有条件true 剩余条件也判断
③
System.out.println(1.1*1.1);
这段代码输出:1.2100000000000002
原因:浮点数不是高精度,浮点数运算会有精度损失
如果想要精确计算,则需把其中一个变量变为double型,代码如下:
int numA = 10 ;
int numB = 4 ;
System.out.println(numA/numB) ; //int/int 还是int型
System.out.println(numA/(double) numB) ;
④
当我们计算字符串和数组长度时需要区分:
数组的length是属性:
int c[]=new int[5];//这种定义方法默认数组初始都为0
int a=c.length //不需要括号
字符串的length是方法,有括号
String r = "123";
int length = r.length();//需要加括号
⑤
在java中:
char+int=int
string+int=string
int number1 = 5;
int number2 = 4;
string a= " ";
a = a + number1 +number2;//输出54,而不是9
只要包含String的+,都做字符串连接,只要出现了字符串类型,不管表达式中相加的是数值类型还是char类型,都会被全部隐式类型转换成字符串,而且这种隐式转换的优先级还高于+。
这是JAVA的装箱机制,最终相当于字符串的连接。
int a=10;
int b=5;
String s="a+b= ";
s+a+b //a+b=105
s+(a+b)//a+b=15
而 int+char=char ,其中int需要强转
char c = 'A';
int num = c + 32 ; // char+int=int ;
char x = (char) num ; // int需要强转