You are on page 1of 7

MILITARY COLLEGE OF SIGNALS

SOFTWARE CONSTRUCTION
Lab Submission: 05
Name: Zahra Qamar
Course: BESE 23C
Experiment # 5: Visibility of Variables in Java

A variable provides us with named storage that our programs can manipulate. Java provides
three types of variables.

 Class variables − Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a block. There would only
be one copy of each class variable per class, regardless of how many objects are created
from it.

 Instance variables − Instance variables are declared in a class, but outside a method.
When space is allocated for an object in the heap, a slot for each instance variable value
is created. Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must be present
throughout the class.

 Local variables − Local variables are declared in methods, constructors, or blocks. Local
variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor, or block.
Task 1:
Write program in java to demonstrate
Class variables
Instance variables
Local variables
Example 1:
Example 2:
Task 2:
Demonstrate that default variables in java would be initialized as local variables, class
variables or instance variables? show by working code?
Default variables would be initialized as local and instance variables, as they appear inside the class. If
not initialized they will have a default value depending upon their type. For example, variable of type int
contains 0 by default, double variable contains 0.0 and string variable contains null.
Local variables do not have a default value and must be initialized, as they are appearing inside any
method or block.

Example 1:
However, if sum is not initialized inside method it takes no default value. It shows the following
error
Example 2:

You might also like