記錄工作中遇到的疑惑點
如有錯解闸盔,請大家一定要幫我在評論中指正,一起進步遗锣,多謝了
- Boolean對象為null货裹,在if中結果是什么?
// 附A
Boolean b = null ;
if (!b){
System.out.println("能打印出來嗎精偿?") ;
}
// 附B
Boolean b = null ;
if (b){
System.out.println("能打印出來嗎弧圆?") ;
}
// 附C
boolean c = true ;
if(b && c){
System.out.println("這個能打印嗎");
}
- 一個對象是null ,能強轉為其它類型嗎笔咽?
// 附A
Boolean b = (Boolean)null ;
String s = (String)null ;
Object o = (Object)null ;
- Integer對象比較用 == 可以嗎搔预?
// 附A
Integer a = 100 ;
Integer a1 = 100 ;
Integer b = 200 ;
Integer b1 = 200 ;
if (a == 100) {
System.out.println("會打印 a == 100 嗎?");
}
if (a == a1) {
System.out.println("會打印 a == a1 嗎叶组?");
}
if (b == 200) {
System.out.println("會打印b == 200 嗎拯田?");
}
if (b == b1) {
System.out.println("會打印 b == b1 嗎?");
}
- 字符串轉Boolean對象甩十,什么情況下是轉成true 船庇?
// 附A
Boolean aBoolean = Boolean.valueOf("");
Boolean a1 = Boolean.valueOf("1");
Boolean aqw2 = Boolean.valueOf("qw2!");
Boolean aTrue = Boolean.valueOf("true");
Boolean aTRUE = Boolean.valueOf("TRUE");
Boolean aFalse = Boolean.valueOf("false");
Boolean aFALSE = Boolean.valueOf("FALSE");
// 附B
boolean a2Boolean = Boolean.parseBoolean("");
boolean a21 = Boolean.parseBoolean("1");
boolean a2qw2 = Boolean.parseBoolean("qw2!");
boolean a2True = Boolean.parseBoolean("true");
boolean a2TRUE = Boolean.parseBoolean("TRUE");
boolean a2False = Boolean.parseBoolean("false");
boolean a2FALSE = Boolean.parseBoolean("FALSE");
- (+- a) 的結果是什么?
int a = 4 ;
int num1 = ( +- a - 1 ) / a ;
int num2 = ( + a - 1 ) / a ;
- 下列程序的輸出結果
String s1 = “abc”;
String s2 = “a”;
String s3 = “bc”;
String s4 = s2 + s3;
System.out.println(s1 == s4);
- 下列程序的輸出結果:
String s1 = “abc”;
final String s2 = “a”;
final String s3 = “bc”;
String s4 = s2 + s3;
System.out.println(s1 == s4);
答案:
- 上面的三個代碼塊都會出現空指向異常侣监。
- null 可以強轉成任意對象鸭轮,但依舊是 null 。
- Integer 小于127都有緩存橄霉,所以小于127可以用 == 比較窃爷,大于127則要用equals才能比較,但最好統一使用equals 姓蜂!
- 只有 “true”和“TRUE” 可以轉換成true ,其它的全部為false .
- 附源碼:
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
public static Boolean valueOf(String s) {
return parseBoolean(s) ? TRUE : FALSE;
}
+a
等價于a
而+- a
等價于- a
, 說白了就是正負a按厘。這是在開發(fā)中出現的小插曲,不小心把( a + b - 1) / b
中的a
給退格了覆糟。當時看到沒有報錯刻剥,居然沒有反應過來false,因為s2+s3實際上是使用StringBuilder.append來完成滩字,會生成不同的對象。
true,因為final變量在編譯后會直接替換成對應的值麦箍,所以實際上等于s4=”a”+”bc”漓藕,而這種情況下,編譯器會直接合并為s4=”abc”挟裂,所以最終s1==s4享钞。