Page 196 - Computer science 868 Class 12
P. 196

7.5 SCOPE OF THE VARIABLES
              Variables are accessed from within the portion where they are created. There are two parts in a program where a
              variable is created. The variables are created directly under a class as data members or inside a method as Local
              variables.

              Now, if a variable is created under a class, the data members can be accessed from anywhere in the class whereas if it
              is a local variable, then it can only be accessed within the method it is created and will have no existence outside the
              method. If it is used outside the method, it will produce an error.
              For example:

                  class Test
                  {
                      int a;
                     Test()
                     {
                          a=5;
                      }
                      void cal()
                      {
                         int x;
                         for(x = 0; x < a; x++)
                         {
                             System.out.println(x);
                          }
                      }
                      void display()
                      {
                         System.out.println(a);
                      }
                  }
              In the above program, the scope of the ‘a’ variable is throughout the program whereas the ‘x’ variable is accessible
              only within the cal() method.
              When a group of statements is written within a curly bracket, then it is known as a compound statement. This group
              of statements executes together in a sequential manner to provide the desired result.

              A compound statement is useful in all types of conditional and iterative statements.
              For example:

                  int i=5;
                  for(; i<=50; i++)
                  {
                      System.out.println(i);
                      if(i%10==0)
                      System.out.print(i + " has 0 in the last");
                  }
              In the above example, the following three statements are inside the for block.
                  System.out.println(i);
                  if(i%10==0)
                  System.out.print(i + " has 0 in the last");
              Hence, they are called compound statements.





                194194  Touchpad Computer Science-XII
   191   192   193   194   195   196   197   198   199   200   201