Last active
December 19, 2018 02:36
-
-
Save HaoyangFan/fc878e34ec06d181f908ef1ece150370 to your computer and use it in GitHub Desktop.
Quick Notes on Java Block Scope
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class BlockScope { | |
| public static void main(String[] args) { | |
| /************ define own block scope without if, for, while is possible ************/ | |
| int n = 3; | |
| // here the block will create a new scope for the variables that are declared inside | |
| { | |
| int i = 5; | |
| // int n = 6; variables that have already been declared outside this scope cannot be redeclared here | |
| n++; // access the variables from outer scope is possible though | |
| System.out.println("Hello world!"); | |
| } // i is only defined up to here | |
| // System.out.println(i); cannot access i outside its defined scope | |
| /** | |
| * When you declare a variable in the rst slot of the for statement, | |
| * the scope of that variable extends until the end of the body of the for loop. | |
| */ | |
| for (int j = 0; j < 2; j++) { | |
| } // j is only defined up to here | |
| String s = "hello"; | |
| switch (s) { // the block for switch will also create a new scope | |
| case "hello": | |
| int i = 4; | |
| System.out.println("hello"); | |
| break; | |
| default: | |
| System.out.println("nope"); | |
| } // variables defined inside block above have scope only up to here | |
| // i++; cannot be accessed in outer scope | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment