Page 333 - Computer_Science_F5
P. 333

Computer Science  (b) Types of Variable
           There are three types of variables in java: local variable, instance variable and static
           variable.


           (i) Local variable
          FOR ONLINE READING ONLY
           Local variables are declared inside the methods, constructors, or blocks. It is usually
           created when the method, constructor or block start to be executed. It is destroyed once
           the method, constructor, or block finishes execution. Local variables are visible only
           within the declared method, constructor, or block. They are implemented internally
           at stack level. There is no default value for local variables, so local variables should
           be declared and an initial value should be assigned before the first use. In this case,
           access specifiers cannot be used for local variables. Program Example 5.1 shows the
           local variable program:

                    Program Example 5.1:

            Java program to demonstrate local variable

              public class Car {
                       public static void main(String[] args) {
                  // Local variable
                  int numOfDoors = 5;  // This variable only exists within this method
                  System.out.println(“My father bought a car with “ + numOfDoors + “ doors.”);
                  }
              }




                                                     variables can also be declared at the
           (ii) Instance variable                    class  level.  Access  modifiers  in  Java,
           This refers to a variable declared within  such as Default,  Private, Protected,
           a class but outside any method. They are  and Public,  restrict  the  scope of these
           declared in a class, not inside a method,  variables,  methods, and constructors.
           constructor, or block. When an object is  By default, instance variables are visible
           allocated in the heap, a storage space is  to all methods, constructors, and blocks
           created for each instance variable. These  within the class. It is recommended to
           variables  hold values that are  needed  make  these  variables  private,  but  they
           by  multiple  methods,  constructors,  can be made visible to subclasses using
           or blocks, or they represent essential  access  modifiers.  Instance  variables
           parts of an object’s state that should be  have default values:
           accessible throughout the class. Instance  (1)  Numbers, the default value is 0,


                                                 324
                                                                for Advanced Secondary Schools



     Computer Science Form 5.indd   324                                                     23/07/2024   12:34
   328   329   330   331   332   333   334   335   336   337   338