Java 變量

2018-08-17 16:50 更新

Java教程 - Java變量


變量由標識符,類型和可選的初始化程序定義。變量還具有范圍(可見性/生存期)。

Java變量類型

在Java中,必須先聲明所有變量,然后才能使用它們。變量聲明的基本形式如下所示:

type identifier [ = value][, identifier [= value] ...] ;

變量定義有三個部分:

  • 類型可以是int或float。
  • identifier是變量的名稱。
  • 初始化包括等號和值。
要聲明指定類型的多個變量,請使用逗號分隔的列表。

int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.

以下變量在一個表達式中定義和初始化。

public class Main {
  public static void main(String[] args) {
    byte z = 2; // initializes z.
    double pi = 3.14; // declares an approximation of pi.
    char x = 'x'; // the variable x has the value 'x'.
  }
}

在聲明之前不能使用變量。

public class Main {
  public static void main(String[] args) {

    count = 100; // Cannot use count before it is declared! 
    int count;
  }
}

編譯上面的代碼會生成以下錯誤消息:


賦值運算符

賦值運算符是單個等號,=。它有這種一般形式:

var = expression;

var 的類型必須與表達式的類型兼容。賦值運算符允許創(chuàng)建一個賦值鏈。

 
public class Main {
  public static void main(String[] args) {
    int x, y, z;
    x = y = z = 100; // set x, y, and z to 100
    System.out.println("x is " + x);
    System.out.println("y is " + y);
    System.out.println("z is " + z);
  }
}

輸出:


動態(tài)初始化

Java允許變量被動態(tài)初始化。在下面的代碼中,Math.sqrt返回2 * 2的平方根,并將結(jié)果直接賦值給c。

public class Main {
  public static void main(String args[]) {

    // c is dynamically initialized
    double c = Math.sqrt(2 * 2);

    System.out.println("c is " + c);
  }
}

上面代碼的輸出是

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號