Java Programming - Operators and Assignments - Discussion

Discussion Forum : Operators and Assignments - Finding the output (Q.No. 1)
1.
What will be the output of the program?
class PassA 
{
    public static void main(String [] args) 
    {
        PassA p = new PassA();
        p.start();
    }

    void start() 
    {
        long [] a1 = {3,4,5};
        long [] a2 = fix(a1);
        System.out.print(a1[0] + a1[1] + a1[2] + " ");
        System.out.println(a2[0] + a2[1] + a2[2]);
    }

    long [] fix(long [] a3) 
    {
        a3[1] = 7;
        return a3;
    }
}
12 15
15 15
3 4 5 3 7 5
3 7 5 3 7 5
Answer: Option
Explanation:

Output: 15 15

The reference variables a1 and a3 refer to the same long array object. When the [1] element is updated in the fix() method, it is updating the array referred to by a1. The reference variable a2 refers to the same array object.

So Output: 3+7+5+" "3+7+5

Output: 15 15 Because Numeric values will be added

Discussion:
43 comments Page 2 of 5.

Sowmya said:   5 years ago
long[] a1={3,4,5};
long[] a2=a1;

This is equal to,
a1[0]=a2[0] and a1[1]=a2[1] and a1[2]=a2[2].

And in fix method, a3 is method local variable it is not an array.
So changes made to a1 is also reflected in a2 so the answer is 15 15.
(3)

Gaurav gupta said:   9 years ago
Long [] a1 = {3, 4, 5};

Long [] a2 = fix (a1) ;

As we know an array itself is a pointer. Here the address of a1 is stored at a2. Therefore when the a1 is changed it will be reflected globally and therefore both have same data.

Vasu said:   1 decade ago
While program is executing
ofter second step
the method of fix(_)
then it comes again back to 3 step.
so it changes the array elements in the position of 1
i.e (a1[1])

Prashant said:   8 years ago
long[] fix(long[] a3) { // a3=a1 and a1= {3,4,5}
a3[1] = 7; // a3[1]=7 means a1[1] will become 7(a1[1]=7), now a1={3,7,5}
return a3;// return a1
}

Anjali said:   9 years ago
When both operands are of the numerical type then the operation is an addition.

If both operands are of string type then it is a concatenation.

Vikas verma said:   1 decade ago
How can the value of a1[1] is change in this prog ?

And a1[] is not given equal to a3[] anywhere in this program.

Can any one Explain this?

Shobu said:   1 decade ago
In java + is used for concatenation. Then why will the algebraic addition of the elements in array take place?

Salik Khan said:   5 years ago
It's because in java array is passed by reference, so any changes in the method reflect in the actual array.

Sarang said:   1 decade ago
a1[0]=3,a1[1]=7,a1[2]=5;a2[0]=3,a2[1]=7,a2[2]=5
a1[0]+a1[2]+a1[3]=15 & a2[0]+a2[2]+a2[3]=15 ..

Rajni said:   8 years ago
Please tell me how to work bubble sort method with easy program? Please explain with an example.


Post your comments here:

Your comments will be displayed after verification.