Skip to content
This repository was archived by the owner on Feb 10, 2024. It is now read-only.

Commit ede1591

Browse files
author
Ram swaroop
committed
added content
1 parent 5bd464d commit ede1591

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

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

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ title: Variables and Literals
66
Variables are devices that are used to store data, such as a number, or a string of character data so that we can
77
manipulate them later in our program. Variables can be broadly classified in to 4 types in Java:
88

9-
1. __Instance__ variables (non-static, declared in a class).
10-
2. __Class__ variables (static, declared in a class).
9+
1. __Class__ variables (static, declared in a class).
10+
2. __Instance__ variables (non-static, declared in a class).
1111
3. __Local__ variables (declared inside a method).
12-
4. __Parameters__ (variables in a method signature).
12+
4. __Block__ variables (variables in static blocks, for-loop blocks etc).
1313

1414
Instance variables and objects reside in heap whereas local variables reside in stack. Consider the below program:
1515

@@ -363,8 +363,18 @@ just stores `00000111` (8 bits) in variable `b` (as `byte` can hold only 8 bits)
363363
left with `10000000` which is not `128` as the 1st bit is the sign bit. So, after computing the 2's compliment of it we
364364
get `-128` as the result.
365365

366+
### Scope
366367

368+
Scope refers to the __lifetime and accessibility of a variable__. In simple words, how long will the variable be hanging
369+
around so that they can be used by other parts of the program. Different types of variables have different scope.
367370

371+
1. __Class or static__ variables have the longest scope. They are created when the class is loaded, and they survive as
372+
long as the class stays loaded in the Java Virtual Machine (JVM).
373+
2. __Instance or non-static__ variables are the next most long-lived. They are created when a new instance is created,
374+
and they live until the instance is removed.
375+
3. __Local__ variables are next. They live as long as their method remains on the stack. As we'll soon see, however,
376+
local variables can be alive and still be "out of scope."
377+
4. __Block__ variables live only as long as the code block is executing.
368378

369379
{% include responsive_ad.html %}
370380

0 commit comments

Comments
 (0)