How to declare variable for specific scope only inside a block with Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        int x = 3; 
        
        if (x == 3) { 
            int z = 15; 
            System.out.println(x + " " + z);      
        }    
        //z = 9;  // Error! z not known here
    }
}



/*
run:

3 15

*/

 



answered May 26, 2019 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        for (int i = 0; i < 4; i++) {      
            int x = 0; 
            
            System.out.println("x : " + x);    
        }
    }
}



/*
run:

x : 0
x : 0
x : 0
x : 0

*/

 



answered May 26, 2019 by avibootz

Related questions

2 answers 260 views
1 answer 170 views
1 answer 216 views
1 answer 154 views
1 answer 89 views
...