Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
- }
Add Comment
Please, Sign In to add comment