W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
變量由標識符,類型和可選的初始化程序定義。變量還具有范圍(可見性/生存期)。
在Java中,必須先聲明所有變量,然后才能使用它們。變量聲明的基本形式如下所示:
type identifier [ = value][, identifier [= value] ...] ;
變量定義有三個部分:
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); } }
輸出:
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); } }
上面代碼的輸出是
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: