<p>What is the output of the following Java program? Explain in terms of how par
ID: 3630812 • Letter: #
Question
<p>What is the output of the following Java program? Explain in terms of how parameters are passed in Java.<br />class Int<br />{<br /> public int value;<br />}<br /><br />class Parameters <br />{<br /> public static void main(String [] args)<br /> {<br /> int value1 = 1;<br /> Int value2 = new Int(), value3 = new Int();<br /> value2.value = 1;<br /> value3.value = 1;<br /> increment(value1, value2, value3);<br /> System.out.println( "value1 = " + value1 +<br /> " value2 = " + value2.value + " value3 = " + value3.value);<br /> }<br /><br /> private static void increment(int value1, Int value2, Int value3)<br /> {<br /> value1++;<br /> value2.value++;<br /> int newValue = value3.value + 1;<br /> value3 = new Int();<br /> value3.value = newValue;<br /> }<br />}</p><p>Suppose a similar program were written in C# in which all the parameters were ref parameters. What would the output of that program be?</p>
<p> </p>
<p>Please explain indepthly the above.</p>
<p> </p>
<p>Thank you!</p>
Explanation / Answer
The output of the program is
value1 = 1 value2 = 2 value3 = 1
1 class Int
2 {
3 public int value;
4 }
5 class Parameters
6 {
7 public static void main(String [] args)
8 {
9 int value1 = 1;
10 Int value2 = new Int(), value3 = new Int();
11 value2.value = 1;
12 value3.value = 1;
13 increment(value1, value2, value3);
14 System.out.println( "value1 = " + value1 +
15 " value2 = " + value2.value + " value3 = " + value3.value);
16 }
17 private static void increment(int value1, Int value2, Int value3)
18 {
19 value1++;
20 value2.value++;
21 int newValue = value3.value+1;
22 value3 = new Int();
23 value3.value = newValue;
24 }
25 }
With variable value1 we don’t have any problem. The variable is passed by value. So the changes made by the function, will not reflect in main function.
Value2 and value3 are two objects. Objects in java are passed by reference.
In line 20 the increment will be affected in the original object of main function. But value3 object in main function has no affect since the operation performed in line 23 is on the object created in line 21 with in the function and this is different from the object created in the main function.
If we change the line 21 as int newValue = value3.value++; then the object of the main function will be affected.
In C#
The output of the program is
value1 = 2 value2 = 2 value3 = 1
Since the variable value1 is passed by reference the change will reflect in the main function. Value2 and value3 are objects. So they behave in similar way as they behaved in java.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.