Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java changing value of a variable through a method? [duplicate]

Tags:

java

Hello I was wondering how I would be able to send a variable as a parameter to a method and have it be changed by the method. For example

public class Main {
    public static void main(String[] args) {
        int i = 2;
        doThis(i);
        System.out.println(i);  
    }

    public static void doThis(int i) {
        i = 3;
    }
}

I would like it to print out 3 instead of 2. Thanks.

like image 616
Tommy Avatar asked May 12 '13 03:05

Tommy


1 Answers

I would like it to print out 3 instead of 2

Change method to return value

int i = 2;
i = doThis(i);


public static int doThis(int i) {
    i = 3;
    return i;
}

it copies the value of primitive from caller to argument

like image 123
jmj Avatar answered Sep 20 '22 12:09

jmj