I'm new to programming. In layman terms, what does it mean when somebody says "Pass a value"?
I was told something like:
public Money (int cost)
Needs to pass a value and I don't understand what is meant.
I'm new to programming. In layman terms, what does it mean when somebody says "Pass a value"?
I was told something like:
public Money (int cost)
Needs to pass a value and I don't understand what is meant.
Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
take the example of that code :
public void Money (int cost)
{
cost = cost + 2;
}
Note that the cost
variable has 2 added to it. Now, suppose that we have some code which calls the method Money:
public static void main(String [] args)
{
int passing = 3;
Money (passing);
System.out.println("The value of passing is: " + passing);
}
In the main method, we set the variable passing
to 3, and then pass that variable to the Money
method, which then adds 2 to the variable passed in.
What do you think the System.out.println
call will print out? Well, if you thought it would print out a 5
you are wrong. It will actually print out a 3
. Why does it print out a 3 when we clearly added a 2 to the value in the Money method?
The reason it prints out a 3
is because Java passes arguments by value – which means that when the call to Money
is made, Java will just create a copy of the passing
variable and that copy is what gets passed to the Money method – and not the original variable stored in the main
method. This is why whatever happens to cost
inside the Money method does not affect the passing
variable inside the main method.
Passing a value is sending a specified value to be used by a method or a class.
In the line you displayed, the value of an integer called cost is passed to the class object Money (I assume it is a class, since classes are usually capitalized) by another object.
The parameters of a method are the values that must be passed by whatever object calls it.
Passing is just sending a value to that object from another object. Whatever is in the parentheses when you call a method or a class is what is being passed to it (though when passed to a class, a constructor must be present).
In Java, from the outcome, you will see that:
when you pass a primitive type of value, like int, double, float, etc, however you modify the value in the accepting method, the value of the original variable won't change.
when you pass an object, if you modify the object data in the accepting method, you're modifying the original object.
Knowing this, you know what outcome you are expecting when you are writing code.
As to the terminology, please refer to other answers/comments for more details.