Number Type Casting(數(shù)字類型強轉(zhuǎn)):
4.5 Number Type Casting(數(shù)字類型強轉(zhuǎn))
隱式 casting(from small to big)
byte a = 111;
int b = a;
顯式 casting(from big to small)
int a = 1010;
byte b = (byte)a;
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
注意: 從大到小必須強轉(zhuǎn)!
一道著名的公司面試題如下,以下程序有何問題?
public class Test {
public static void main(String[] args) {
short s1 = 1;
s1 = s1 + 1;
System.out.println(s1);
}
}
上面這個程序,因為1是int,s1是short,所以s1+1就往大的隱形轉(zhuǎn),就自動變成int,所以這個式子s1 = s1 + 1;左邊是short,右邊是int, 當把大的變成小的時,需要強轉(zhuǎn)。正確的程序見下:
public class Test {
public static void main(String[] args) {
short s1 = 1;
s1 =(short) (s1 + 1);
System.out.println(s1);
}
}
輸出結(jié)果:
2
4.6 轉(zhuǎn)義符
換行 \n
水平制表符 \t
退格符 \b
回車符 \r
使用轉(zhuǎn)義字符‘\’來將其后的字符轉(zhuǎn)變?yōu)槠渌暮x,例如,如果需要在java中使用一個絕對路徑:c:\hua\java,如果直接在程序中寫String path = “c:\hua\java”,則不會得到你期望的結(jié)果,因為
n是 字母, \n死規(guī)定就是換行,
\是 轉(zhuǎn)義的作用, \\死規(guī)定就是路徑。
所以,這時候應(yīng)該這樣來寫:
String path = “c:\\hua\\java”;
public class Test {
public static void main(String[] args) {
String path = "c:\\hua\\java";
System.out.println("path " + path);
/*下面一句話直接報錯 @馬克-to-win*/
// String path = "c:\hua\java";
}
}
輸出:
path c:\hua\java