Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Feb 10, 2024. It is now read-only.

Commit d841753

Browse files
author
Ram swaroop
committed
added content
1 parent f069d8f commit d841753

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎_posts/2015-05-14-variables-and-literals.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,42 @@ and they live until the instance is removed.
376376
local variables can be alive and still be "out of scope".
377377
4. __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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /