Hi, I just started my java class a few weeks ago, I have a question if you guys can help me.
I`m learning about passing arguments, so I have this small code, it works perfect, the output is " 42 84 ", but I didn`t get it. what does it mean when they say the variables that are passed by value can`t change, if after it`s passed it can be multiplied, and changed?

I just want to understand this and be clear about it.

Here is the code:

class Arg
   {
       public static void main(String[] args)
      {
         int orig = 42;
         Arg x = new Arg();
         int y = x.go(orig);
      
         System.out.println(orig + " " + y);
      }
   
       int go(int arg)
      {
         arg = arg * 2;
      
         return arg;
      }
   }

Thanks

Recommended Answers

All 3 Replies

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.

The value of the actual parameter is copied into the formal parameter when the procedure is invoked. Any modification of the formal parameter affects only the formal parameter and not the actual parameter.

public class Arg
{
    public static void main(String[] args)
   {
      int orig = 42;
      Arg x = new Arg();
      int y = x.go(orig);
   
      System.out.println(orig + " " + y);
   }

    int go(int arg)
   {
    	arg = 52;
      arg = arg * 2;
   
      return arg;
   }
}

you get : 42 104

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.

The value of the actual parameter is copied into the formal parameter when the procedure is invoked. Any modification of the formal parameter affects only the formal parameter and not the actual parameter.

public class Arg
{
    public static void main(String[] args)
   {
      int orig = 42;
      Arg x = new Arg();
      int y = x.go(orig);
   
      System.out.println(orig + " " + y);
   }

    int go(int arg)
   {
    	arg = 52;
      arg = arg * 2;
   
      return arg;
   }
}

you get : 42 104

so arg can change and orig can`t?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.