Java 变量

Java教程 - Java变量

变量由标识符类型可选的初始化程序定义。变量还具有范围(可见性/生存期)。

Java变量类型

在Java中,必须先声明所有变量,然后才能使用它们。变量声明的基本形式如下所示:

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

变量定义有三个部分:

  • 类型可以是intfloat
  • 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 的类型必须与表达式的类型兼容。赋值运算符允许创建一个赋值链。

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);
  }
}

输出:

x is 100
y is 100
z is 100

动态初始化
Java允许变量被动态初始化。在下面的代码中,Math.sqrt返回2 * 2的平方根,并将结果直接赋值给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);
  }
}

上面代码的输出是

c is 2.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值