@@ -6,10 +6,10 @@ title: Variables and Literals
6
6
Variables are devices that are used to store data, such as a number, or a string of character data so that we can
7
7
manipulate them later in our program. Variables can be broadly classified in to 4 types in Java:
8
8
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).
11
11
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 ).
13
13
14
14
Instance variables and objects reside in heap whereas local variables reside in stack. Consider the below program:
15
15
@@ -363,8 +363,18 @@ just stores `00000111` (8 bits) in variable `b` (as `byte` can hold only 8 bits)
363
363
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
364
364
get ` -128 ` as the result.
365
365
366
+ ### Scope
366
367
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.
367
370
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.
368
378
369
379
{% include responsive_ad.html %}
370
380
0 commit comments