settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: How are the arguments passed in methods in java

+10 votes

I have 2 questions:

  1. In Java how are the arguments passed in methods? By reference or by copy?
  2. Can you give some code examples? thanks
asked in Java category by user richard8502
edited by user golearnweb

1 Answer

+2 votes
 
Best answer

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!

 

answered by user john7
selected by user golearnweb
...