Java基礎--關鍵字、資料型別、型別轉換
阿新 • • 發佈:2020-07-22
關鍵字(35個)
檢視Java關鍵字
資料型別
Java是強型別語言:要求變數的使用嚴格符合規定,所有變數都必須先定義後才能使用
弱型別語言:JavaScript
Java的資料型別分為兩大類:基本資料型別、引用型別
public class Demo02 { public static void main(String[] args) { // 8大基本資料型別 byte a = 20; short b = 1; int c = 2; long d = 1000L; float e = 3.1f; double f = 4.20; char ch = 'a'; boolean flag = true; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); System.out.println(e); System.out.println(f); System.out.println(ch); System.out.println(flag); } }
public class Demo03 { public static void main(String[] args) { //============================================= // 整數拓展: 進位制 二進位制 八進位制 十進位制 十六進位制 //============================================= int i = 10; int i2 = 010; int i3 = 0x12; System.out.println(i); System.out.println(i2); System.out.println(i3); //============================================= // 浮點拓展 銀行算錢 // BigDecimal 數學工具類 //============================================= // float 有限 離散 舍入誤差 接近但不等於 float f = 0.1f; double d = 1.0/10; System.out.println(f==d); // false float d1 = 23232434344354545f; float d2 = d1 + 1; System.out.println(d1==d2); // true //============================================= // 字元拓展 // 所有字元的本質都是數字 //編碼 Unicode 2位元組 0-65536 Excel 2的16次方=65536 // A 65 a 97 // U0000 - UFFFF // 轉義字元 // \t \n \b //============================================= char c1 = 'a'; char c2 = '中'; char c3 = '\u0061'; System.out.println(c1); System.out.println((int)c1); System.out.println(c2); System.out.println((int)c2); System.out.println(c3); String sa = new String("hello world"); String sb = new String("hello world"); // 涉及到物件的記憶體分析 String sc = "hello world"; String sd = "hello world"; System.out.println(" // ========================"); System.out.println(sa==sb); // 不等 System.out.println(sc==sd); // 等 //============================================= // 布林拓展 //============================================= boolean flag = true; if(flag==true){} // 新手 if (flag) {} //老手 } }
型別轉換
強制轉換 : 高到低
自動轉換: 低到高
強制轉換需要注意點:
1).不能對布林型別進行轉換。
2).把一個浮點數強制轉換為整數時,java會直接截斷浮點數的小數部分。
3).把一個超出資料範圍的數值賦給資料型別是,會出現資料溢位的情況,造成資料的缺失。
public class Demo06 { public static void main(String[] args) { //操作比較大的數的時候,注意溢位問題 // JDK7的新特性 數字之間可以用下劃線分割 int money = 10_0000_0000; int years = 20; int total = money * years; // 1474836480, 計算的時候溢位了 long total2 = money * years; // 預設是int, 轉換之前就存在溢位了 long total3 = money * ((long) years); System.out.println(total3); } }