This repository was archived by the owner on Feb 10, 2024. It is now read-only.
File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -376,7 +376,42 @@ and they live until the instance is removed.
376376local variables can be alive and still be "out of scope".
3773774 . __ Block__ variables live only as long as the code block is executing.
378378
379+ Below program shows all types of variables and explains their scopes too. Please refer to the comments to understand which
380+ are __ in scope__ and which are __ out of scope__ .
379381
382+ {% highlight java linenos %}
383+ class Scope {
384+ static int s = 343; // static variable
385+ int x; // instance variable
386+
387+ { // initialization block
388+ x = 7;
389+ int x2 = 5; // block variable
390+ }
391+
392+ Scope() { // constructor
393+ x += 8;
394+ int x3 = 6;
395+ }
396+
397+ void doStuff() { // method
398+ int y = 0; // local variable
399+ for (int z = 0; z < 4; z++) { // 'for' code block
400+ y += z + x;
401+ }
402+ z++; // compiler error (out of scope)
403+ x2++; // compiler error (out of scope)
404+ }
405+
406+ public static void main(String[] a) {
407+ x++; // compiler error! 'x' is instance variable, so
408+ // we need an object to access it
409+ x2++; x3++; // compiler error! block variables scope
410+ // is only inside the block in which they
411+ // are declared
412+ }
413+ }
414+ {% endhighlight %}
380415
381416
382417
You can’t perform that action at this time.
0 commit comments