Questions and Answers
What is the output of: Object x = "whoot"; object y = x; x = null; System.out.println(y);
whoot
What is the output of: Object a = "whoot"; object b = a; b = null; System.out.println(a);
whoot
What happens in the method mystery(Object one, Object two) when called with (g, h)?
It prints the value of 'h'.
What is printed after calling test.mystery2(z, w)?
Signup and view all the answers
What will happen if test.mystery3(list) is called?
Signup and view all the answers
Study Notes
Java Object References and Outputs
- When an object is assigned to another variable, both variables point to the same memory location.
- In the example with
Object x = "whoot";
andObject y = x;
, settingx
tonull
does not affecty
, which still references "whoot". - Output of
System.out.println(y);
is "whoot".
Variable Reassignment and Object Output
- Reassigning variable
b
tonull
afterb = a;
does not change the original object referenced bya
. - Therefore,
System.out.println(a);
also outputs "whoot".
Method Parameter Passing
- In Java, object references are passed by value; modifying the parameter does not change the original object outside the method.
- In
mystery(Object one, Object two)
, settingone = two;
only changesone
locally.out.println(one);
outputs the value oftwo
, which isn't affected.
Method Behavior with Primitive Types
- For
mystery2(int one, int two)
, even thoughone
is set totwo
, it does not change the values ofz
orw
due to primitive type passing. - Consequently,
System.out.println(z + " " + w);
retains the original values.
Array References in Methods
- In
mystery3(Object[] ray)
, assigningray
to a new array or object does not affect the original reference outside the method. - The modification of
ray
withinmystery3
is local.
Final Output Considerations
- Outputs do not reflect changes in method parameters or reassigned objects in the main context.
- Understanding memory allocation and how Java handles object references is crucial to predict outputs accurately.
Studying That Suits You
Use AI to generate personalized quizzes and flashcards to suit your learning preferences.
Description
Test your knowledge on Java object references, variable reassignment, and method parameter passing. This quiz covers the critical concepts of memory locations, reference behavior, and the distinction between object and primitive type handling in Java.