Java Programming - Operators and Assignments - Discussion

Discussion Forum : Operators and Assignments - Finding the output (Q.No. 13)
13.
What will be the output of the program?
class Two 
{
    byte x;
}

class PassO 
{
    public static void main(String [] args) 
    {
        PassO p = new PassO();
        p.start();
    }

    void start() 
    {
        Two t = new Two();
        System.out.print(t.x + " ");
        Two t2 = fix(t);
        System.out.println(t.x + " " + t2.x);
    }

    Two fix(Two tt) 
    {
        tt.x = 42;
        return tt;
    }
}
null null 42
0 0 42
0 42 42
0 0 0
Answer: Option
Explanation:

In the fix() method, the reference variable tt refers to the same object (class Two) as the t reference variable. Updating tt.x in the fix() method updates t.x (they are one in the same object). Remember also that the instance variable x in the Two class is initialized to 0.

Discussion:
21 comments Page 2 of 3.

Aara said:   1 decade ago
Are the objects passed by reference? Java is pass by value right?

Aditi said:   1 decade ago
Where is the instance variable x initialized to 0?

Adhikari said:   10 years ago
Don't understand, can you explain the logic?

Sowmya said:   10 years ago
Can you explain clearly regarding the logic?

Sanjyoti said:   9 years ago
Can anyone explain it step by step, please?

AJAXX said:   1 decade ago
Yes Dude, Objects are passed by Reference.

Likhith said:   8 years ago
Here, both t.x and tt.x are changed to 42.

Ashish said:   8 years ago
string is immutable in java.

Lavanya said:   10 years ago
Can any explain this program?

Sowmya said:   10 years ago
Then how do we get 42?


Post your comments here:

Your comments will be displayed after verification.