Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Explain in terms of how parameters are passed in Java. import java.awt.*; class

ID: 3554993 • Letter: E

Question

Explain in terms of how parameters are passed in Java.

import java.awt.*;

class PointParameters
{
public static void main(String [] args)
{
int x = 1, y = 1;
Point p = new Point(x, y), q = new Point(x, y);
doubleScale(x, y, p, q);
System.out.println( "(x,y) = " + new Point(x, y) +
" p = " + p + " q = " + q);
}

private static void doubleScale(int x, int y, Point p, Point q)
{
x *= 2;
y *= 2;
p.x *= 2;
p.y *= 2;
q = new Point(x, y);
}
}

Suppose a similar program were written in C# in which all the parameters were ref parameters. What would the output of that program be?

Explanation / Answer

JAVA Behaviour

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references and those references are passed by value.

It goes like this:

In this example aDog.getName() will still return "Max". d is not overwritten in the function as the object reference is passed by value.

So in your example, output will be :

'x and y' will remain same;

p.x and p.y will become double and change.

q.x and q.y will remain same too because in function a new object is formed instead of changing previous one.

So x = 1 , y = 1 , p.x = 2 , p.y = 2 , q.x = 1, q.x = 1;

Now in C# pass by reference :

Since it would be pass by reference, So " x, y, p.x,p.y,q.x,q.y " all will change .

So x = 2 , y = 2 , p.x = 2 , p.y = 2 , q.x = 2, q.x = 2;

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote