Question

What is printed by running the following code? public static void main(String[] args) { int[] nums...

What is printed by running the following code?

public static void main(String[] args) {

int[] nums = {2, 3, 4};

int n = 5;

changeMe1(n, nums);

System.out.print( n );

System.out.print(nums[0]);

changeMe2(n, nums);

System.out.print( n );

System.out.print(nums[0]);

}

public static void changeMe1(int number, int[] list) {

number++;

list[0]++;

}

public static void changeMe2(int number, int[] list) {

number = 9;

list = new int[1];

list[0] = 99;

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1


class Outpt
{

public static void main(String[] args) {

int[] nums = {2, 3, 4};

int n = 5;

changeMe1(n, nums);

System.out.print( n );   // n still remains same after function call

System.out.print(nums[0]);

changeMe2(n, nums);

System.out.print( n ); // n still remains same after function call

System.out.print(nums[0]);

}

public static void changeMe1(int number, int[] list) {

number++;   //value of local variable number incremented but not reflected in variable n in main since it is a pass by value call for changeMe1

list[0]++; ////array is passed by reference and first value incremented and is reflected in original array nums in main

}

public static void changeMe2(int number, int[] list) {

number = 9; //value of local variable number changed to 9 but not reflected in variable n in main since it is a pass by value call for changeMe1

list = new int[1]; //array is passed by reference but here it is locally defined as a single variable array and given value 99 which is not reflected in original array nums in main

list[0] = 99;

}
}

// Thus the output of program is : 5353

Add a comment
Know the answer?
Add Answer to:
What is printed by running the following code? public static void main(String[] args) { int[] nums...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT