Hi Could you please explain me why is this output public cla

Hi!

Could you please explain me why is this output?

public class MethScope2
{
   public static void main(String [] args)
   {
      Laugh clown = new Laugh();
      clown.around();
      clown.report();
      clown.joke();
      clown.report();
   }
}

class Laugh
{
   int loud = 3;
  
   public void around()
   {
      int loud = 10;
   }
  
   public void joke()
   {
      int loud = 20;
   }
  
   public void report()
   {
      System.out.println(loud);
   }
}

Answer is : 3 3

Solution

In the given code, the variable loud is declared both as a class member variable and also as local variables inside the different functions. You might be aware of a concept called as \"scope of the variable\". The scope of the variable determines the existance of a variable and the value it holds during the entire program life cycle. For example, consider the simple code shown below:

class xyz{

int x = 5;

public static void main(String args[]){

int x = 10;

}

}

In the above code, when x is first defined as soon as the class is declared as a class member variable, the lifetime of x is will be till the end of the complete program or destruction of class (in heap memory). As the program is composed of the class and as soon as the main () gets over with, the memory reserved for the class xyz gets deallocated, and hence x dies. Now consider the variable x defined inside main() as a local variable. The scope of the variable x is solely limited to the function only and not the entire class or program lifetime. Now, the interesting question is, what happens to the x originally declared earlier, and inside the main function which x is going to rule ? While the class variable x still exists, however it is not going to rule inside the function. Inside the main function, the local variable dominates over the class variable, and hence if we want to print x inside main(), then it prints the value of the local variable x.

Now coming back to the question asked. In this case, the class variable laugh is defined to be 3 and there are several local variables defined inside every functions (around and joke), which declare and define new values of laugh, all of which are limited to the scope of the respective functions. Thus, while printing the value of laugh in the report function, it prints the value of the class variable laugh, which is 3.

Hi! Could you please explain me why is this output? public class MethScope2 { public static void main(String [] args) { Laugh clown = new Laugh(); clown.around(
Hi! Could you please explain me why is this output? public class MethScope2 { public static void main(String [] args) { Laugh clown = new Laugh(); clown.around(

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site