|
|
|
Program "Scope1" | Program "Scope2" |
---|---|
public class Scope1 { public static void main(String[] args) { double r; r = 3.14; System.out.println(r); } } |
public class Scope2 { public static void main(String[] args) { { double r; r = 3.14; } System.out.println(r); } } |
The only difference is we put the definition of the variable r inside a block in Program "Scope2"
|
How to run the program:
|
|
That is why the variable r is not accessible in program Scope2.java:
On the other hand, the variable r is accessible in program Scope1.java:
|
|
public class Scope3 { public static void main(String[] args) { { r = 1; // (1) double r; r = r + 5; // (2) } r = r + 2; // (3) } r = r + 3; // (4) } |
Questions:
|
Answers:
|
|
|
Example: this is not allowed
public class Scope7 { public static void main(String[] args) { /* ------------------------------------------- 2 variables named r inside the SAME scope ------------------------------------------- */ double r = 0.0; int r = 0; // Error ! System.out.println(r); } } |
How to run the program:
|
Error message:
Scope7.java:10: r is already defined in main(java.lang.String[]) int r = 0; ^ 1 error |
|
Multiple pairs of braces can form 2 configurations
|
There are no other possible configuration
|
Example: the following 2 blocks create disjoint (non-overlapping) scopes
|
Example:
|
How to run the program:
|
|
Example: the following 2 blocks create a nested scopes
The enclosing block forms the outer scope
The enclosed block forms the inner scope
|
Example:
|
public class Scope5 { public static void main(String[] args) { { double r = 3.14; { r = 5; // No error t = 5; // Will cause "undefined variable" error } double t = 1.0; } } } |
How to run the program:
|
public class Scope6 { public static void main(String[] args) { { // Start of outer scope double r; { // Start of inner scope String r; ... } } } } |
The first definition of the variable r takes places inside the outer scope
The second definition of the variable with the same name r takes places inside the inner scope
|
|
Answer:
|
|
public class Exercise1 { public static void main(String[] args) { { double r = 3.14; { String s = "1234"; r = r + 2; System.out.println( s + r ); } { int s = 1234; System.out.println( s + r ); } } } } |
Answer:
12345.14 1239.14 |
How to run the program:
|
public class ScopeX { public static void main(String[] args) { { String r = "abc" ; System.out.println(r); } double r = 4.0; System.out.println(r); } } |
Does it violate the rule:
|
Answer:
|
How to run the program:
|