PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] Why does the method change passed array's value

 July 06, 2022     algorithm, arrays, java, oop, pass-by-reference     No comments   

Issue

I am making changes in a local variable and returning it. I think it should print 12 at line no 9.

public class HackerEarth {

    int a[]= {3,4,5};
    int b[]=foo(a);

    void display() {
        System.out.println(a[0]+a[1]+a[2]+ " "); //line no 9
        System.out.println(b[0]+b[1]+b[2]+ " ");
    }

    public static void main(String[] args) {
        HackerEarth he=new HackerEarth();
        he.display();
    }
    private int[] foo(int[] a2) {
        int b[]=a2;
        b[1]=7;
        return b;
    }
}

Any suggestion would be appreciated.


Solution

You're using the reference to the first array to overwrite it's value in foo method. To create another array based on values of the passed ones, consider using Arrays.copyOf:

private int[] foo(int[] a2) {
    int b[] = Arrays.copyOf(a2, a2.length);
    b[1]=7;
    return b;
}


Answered By - Andronicus
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing