天天看點

我的JAVA學習之路(第四天)-------資料類型

(參考網易雲課堂:龍馬高新教育)

一、各種資料類型所占空間(沒必要去記憶,了解即可)

①基本

字 節------byte------1位元組

短整型------short------2位元組

整 型------ int ------4位元組

長整型------ long------8位元組

布爾型------boolean—1bit

單精度------ float ------4位元組

雙精度------double------8位元組

字 符------ char ------2位元組

②包裝類

整數類型對應的包裝類

為什麼引入包裝類?萬物即對象,而像byte、short等不是對象,是以由包裝類引入對象的概念;

通常在後面加一個.可以得到其屬性;

詳細見下面的代碼

byte------Byte

short------Short

int------Integer

long-----Long

float-----Float

double-----Double

char------Character

public static void main(String[] args) {
    byte byte_max = Byte.MAX_VALUE;   //最大值
    byte byte_min = Byte.MIN_VALUE;   //最小值
    System.out.println("the maximum of byte is "+byte_max);
    System.out.println("the minimum of byte is "+byte_min);
    System.out.println("byte對應的比特位"+Byte.SIZE); 
    System.out.println("byte對應的類型"+Byte.TYPE);
  }      

小補充

在Java中數字預設是int類型;

是以在初始化指派long類型時候應該 long 變量 = 1L;(L小寫也可)

​​

​int num = 1;​

​​ //定義一個int類型

​​

​long num1 = 1;​

​​ //設計自動轉換,因為在java中預設數字為int類型

​​

​long num 2 = 2L;​

​​ //定義一個long類型

char ch = 91; 代表ch為’a‘;

當要檢視 字元對應的ASCII碼時

可以​​

​int ch2 = 'a';​

​​ 同理可以檢視中文的GBK碼表,此編碼表也相容ASCII碼;

這裡同時拓展一下Unicode:将所有國家的編碼表融合到一個表中

🌂布爾類型(沒啥好說的)

boolean b1 = true;
    boolean b2 = false;
    System.out.println(b1);
    System.out.println(b2);      

二、資料類型轉換(也沒啥好說的前面說過)

但注意差別下這個的結果

int a = 55,b = 9;
    float g,h;
    g=a/b;
    h=(float)a/b;
    System.out.println(g);   //6.0
    System.out.println(h);   //6.111111      

三、基本資料類型的預設值

成員變量有預設值,而局部變量沒有

下面即為成員變量的預設值:

byte—(byte)0;

short—(short)0;

int—0;

long—0L;

float—0.0F;

double—0.0D;

char— ’ '或\u0000(也代表空,它為Unicode字元) 列印時像這樣使用’\u0000‘

boolean—false;

四、拓展

🌂(布爾類型)在c\c++中規定所有非零數即為真,零為假;而在Java中,布爾變量隻有true與false兩個變量,除此之外沒有其他的任何值,因而它和任何數字都無關;

①列印int類型中最小值到最大值是否為偶數

public static void main(String[] args) {
    for(int i = Integer.MIN_VALUE;i<=Integer.MAX_VALUE;i++)
    {
      boolean isEven = (i%2==0);
      System.out.println("i = "+i+",isEven = "+isEven);
也等價于    System.out.println("i=%d,isEven=%b",i,isEven);
    }      

②拼接符号的使用

🌂“+”的功能:加法運算與拼接符号

加法運算:隻有數字的時候,結果得到數字;

拼接符号:有字元串的時候,與字元串進行相加,得到字元串;

public static void main(String[] args) {
    int x1 = 5;
    int x2 = 2;
    System.out.println(x1+x2);
    System.out.println(x1+x2+"1");
    System.out.println(x1+x2+"K");
    System.out.println("A"+x1+x2);
  }