0

Sorry for my some stupid question but I've learned that parameters in Java passed by value. If I write code like this, i get 69, not 690 because in this method I changed the copy of variable num.

public class Main
{
    public static void main(String[] args)
    {
        int num = 69;
        mystery(num);
        System.out.println(num); //69
    }
    public static void mystery(int num)
    {
        num *= 10;
    }

}

But in this example values of my array are changed!!! And I don't understand why, cause I thought parameters passed by value!!

public class Main
{
    public static void main(String[] args)
    {
        int[] a = {1,2,3,4,5};
        mystery2(a);
        for(int e : a)
        {
            System.out.print(e + " "); // 10 20 30 40 50
        }
    }
    public static void mystery2(int[] array)
    {
        for(int i = 0; i < array.length; i++)
        {
          array[i] *= 10;
        } 
    }
}  
      
    
    

  • 4
    Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – OH GOD SPIDERS Mar 29 '21 at 14:35
  • You cannot assign to `array` an other array (or null), but the fields may be assigned. The rule is `f(x)` - passing a variable x to f - will never change the variable's value. But fields of that value may be changed. The reason: safer code; no changing of variables on a call. – Joop Eggen Mar 29 '21 at 14:38
  • I found this to be very helpful. It's for c# but I believe it applies to java the same. https://jonskeet.uk/csharp/parameters.html – vbp13 Mar 29 '21 at 14:38
  • ookay now I've figured it out a bit, thanks a lot, @JoopEggen – Nurtugan Azatbekuly Mar 29 '21 at 14:51

0 Answers0