范围和块有什么区别?

我在一本书中看到了一段代码,如下所示:

x = 10; if(x ==10) { // start new scope int y = 20; // known only to this block x = y * 2; } 

代码和块都是一样的吗?

范围是您可以引用变量的位置。 块定义block scope定义的变量将仅在该块内定义,并且在块结束后不能引用它。

所以在这段代码中,如果你尝试类似的东西:

 x = 10; if(x ==10) { // start new scope int y = 20; // known only to this block x = y * 2; } y = 5; // error y is out of scope, not it is not defined 

因为你在这里有一个本地范围
java中的其他类型的作用域是class scope (例如),类的成员具有类作用域,因此可以在类中的任何位置访问它。

范围的基本规则是:

  1. 参数声明的范围是声明出现的方法的主体。
  2. 局部变量声明的范围是从声明出现的点到该块的结尾。
  3. 出现在for语句头部的初始化部分中的局部变量声明的范围是for语句的主体和头部中的其他表达式。
  4. 方法或字段的范围是类的整个主体。 这使得类的非静态方法可以使用类的字段和其他方法。

从Java语言规范 :

14.2。 块 :

块是大括号内的语句,本地类声明和局部变量声明语句的序列。

6.3。 宣言的范围

声明的范围是程序的区域,声明中声明的实体可以使用简单的名称引用,只要它是可见的(第6.4.1节)。

在块中,您可以声明变量。 范围定义了区域,您可以通过其简单名称访问声明的变量。

当涉及到条件和循环时,如果你没有指定{}那么立即跟随语句是唯一属于特定条件或循环的语句

例如

 x = 10; if(x ==10) { int y = 20; x = y * 2; } both lines get executes only if condition returns TRUE x = 10; if(x ==10) int y = 20; x = y * 2; // this is not belong to if condition. therefore it will execute anyway 

他们大多是一样的。

块是由{和}包围的一些代码。 范围是程序的一部分,其中某些东西是可见的。 据我所知,所有块都创建了范围 – 块中定义的任何块都不在块外。 相反的情况并非如此。

以下是一些没有块的范围:

 for(int k = 0; k < 10; k++) { // k<10 and k++ are in a scope that includes k, but not in a block. System.out.println(k); // this is in a block (the {}) } for(int k = 0; k < 10; k++) // k<10 and k++ are in a scope that includes k, as above System.out.println(k); // but there's no block! class Test { // this is a scope but not a block. Not entirely sure about this one. int x = 2; int y = x + 1; // I can access x here, but not outside the class, so the class must be a scope. } 

根据Block的定义

块是平衡括号之间的一组零个或多个语句,可以在允许单个语句的任何位置使用。

所以

 { //block started } //block ended 

在块内声明的变量是什么,范围仅限于该块。

这有道理吗?

oracle文档将块定义为

块是平衡括号之间的一组零个或多个语句,可以在允许单个语句的任何位置使用

@ Mhd.Tahawi已经告诉了范围是什么。

有一点我应该指出,

 switch(something){ case somethin1: line1 line2 break; case someting2: line3 line4 break; } 

第{1,2,3,4}行在同一范围内因此阻止因为我没有用括号开始和结束每个案例。 与python不同,缩进并不意味着阻塞

Scope是指visibility of variablesvisibility of variables 。 换句话说,程序的哪些部分可以查看或使用它。 通常,每个变量都具有全局范围。 一旦定义,程序的每个部分都可以访问变量。

能够将变量的范围限制为单个function/block非常有用。 该变量的范围有限。 这样, function/block内的更改不会以意外的方式影响主程序。