As you stated in your question: there are 2 types of passing an argument in methods in various different programming languages:
-
Passing to a method by COPY: The method recieves a copy of the variable
-
Passing to a method by REFERENCE: The method recieves a reference to the origianl object
In Java the arguments ARE ALWAYS PASSED BY COPY!
Here is some code with given examples:
public class ArgumentsPass {
public static void main(String[] args) {
int original = 10;
System.out.println("Original int before: " + original);
incrementValue(original);
System.out.println("Original int after: " + original);
System.out.println("**********************************");
String original2 = "Original!";
System.out.println("Original String before: " + original2);
changeString(original2);
System.out.println("Original String after: " + original2);
}
static void incrementValue(int inMethod) {//METHOD 1: incrementValue
inMethod++;
System.out.println("In method int is: " + inMethod);
}
static void changeString(String inMethod) {//METHOD 2: changeString
inMethod = "New!";
System.out.println("In method String is: " + inMethod);
}
}
The output is:
Original int before: 10
In method int is: 11
Original int after: 10
**********************************
Original String before: Original!
In method String is: New!
Original String after: Original!