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;
}
}
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 1 of 3.
Aara said:
1 decade ago
Are the objects passed by reference? Java is pass by value right?
AJAXX said:
1 decade ago
Yes Dude, Objects are passed by Reference.
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 .
Aditi said:
1 decade ago
Where is the instance variable x initialized to 0?
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.
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.
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.
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).
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).
Lavanya said:
10 years ago
Can any explain this program?
Karthi said:
10 years ago
Explain me?
Adhikari said:
10 years ago
Don't understand, can you explain the logic?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers