Michael O'Hara
Michael O'Hara

Reputation: 33

Java - point me in the right direction

I am doing some work on Java as part of my course, question I am stuck on is:

Consider the following code illustrating the class MyClass, its instance variables i and j, and its single method foo:

class MyClass
{
 int i = 0; 
 int j = 10; 

 public void foo() 
 { 
    j = 20;
    {
       int j = 11;
       i = 10;
       j = 10;
    }
    System.out.println("i, j = " + i + ", " + j); 
 } 
}

Suppose we construct an object of this class and invoke its method foo, what would the output from method foo be?

I have been struggling with it for a while now. At first I thought it was something to do with increment operators, or for/while loops, but I'm not sure.

I am not looking for someone to give me the answer, but I could really do with a nudge in the right direction.

Upvotes: 1

Views: 168

Answers (2)

Rahul
Rahul

Reputation: 107

Your code is a good example of Shadowing. In curly braces { ... } since you have declared/initialized int j = 11;

So within the curly braces, whatever value you assign to it, it will be lost at the moment when your code leaves the curly braces.

But, since 'i' is only declared as an instance variable and then initialized within the curly braces, so it sustains the value of 10 assigned to it within the curly braces and retains it even outside curly braces.

Therefore, your output will be i, j = 10, 20

Read about Shadowing in Java. Hope it answers your question..

Upvotes: 0

nitishagar
nitishagar

Reputation: 9413

I have annotated the code for better understanding:

class MyClass
{
 int i = 0; 
 int j = 10; 

 public void foo() 
 { 
    j = 20;
    { // code block 
       int j = 11; // new J only lives till the curly brace ends (local scope)
       i = 10; // i updated 
       j = 10; // the new scoped j variable updated
    } // new scoped j not available now
    // original j (20) and old i with updated value available
    System.out.println("i, j = " + i + ", " + j); 
 } 
}

Upvotes: 2

Related Questions