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.

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

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

Karthi said:   10 years ago
Explain me?

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

Sherif said:   1 decade ago
Two t = new Two();
Two t2 = new Two();
t2=t;

This mean there are two different objects with two different references.
in this case the output will be (0 0 42).

Anup singh said:   1 decade ago
Q. Why values are not updating here?

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

void start()
{
String name1 = "hello";

String name2 = afix(name1);

System.out.println(name1+" "+name2);
}

String afix(String nm)
{
nm = "bye";
return nm;
}
}

Result: hello bye.

Hussain said:   1 decade ago
In java all primitive types have there default vale like for int is 0, boolean is false so is with byte.

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

Rakesh said:   1 decade ago
There is no concept of pass by reference in java . JAVA is purely pass by value . when objects are passed they are also passed by value . since in the called method and calling method the object the references are pointing is same you get the values reflected in calling method .

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


Post your comments here:

Your comments will be displayed after verification.