0

Why am I getting an output equals 5? I was expecting 6, because after the "addthenumber(x);" line, the method is called, and what I am thinking is the method performs the calculation and 5 becomes 6. So sysout should print 6, but how is it 5?

public class CodeMomkeyPassingvalue 
{
    public static void main(String[] args) 
    {
        int x = 5;
        addthenumber(x);
        System.out.println(x);
    }

    private static void addthenumber(int number) 
    {
        number = number+1;
    }
}

output:

5
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Jboy
  • 21
  • 1
  • 9

3 Answers3

6

Arguments to methods are passed by value, not by reference. That means that not the variable itself, but only the value of the variable is passed to the method.

The variable number inside the method addthenumber is not the same variable as the variable x in the main method. When you change the value of number, it does not have any effect on the variable x in main.

Jesper
  • 202,709
  • 46
  • 318
  • 350
0

Java follows the call by value paradigma, so the value is not changed in the calling function. If you would like to change the value you have to return it after adding 1;

public static void main(String[] args) 
{
    int x = 5;
     x = addthenumber(x);
    System.out.println(x);
}

private static int addthenumber(int number) 
{
    return number+1;
}
Jens
  • 67,715
  • 15
  • 98
  • 113
0

Below code

 {

        int x = 5; // declare x = 5 here

        addthenumber(x); // calling function, passing 5

catch is here - Arguments are passed by value, not by reference. x itself is not passed, only the value of the x is passed to the method.

        System.out.println(x); // printing same x value here, ie 5

    }

private static void addthenumber(int number) {

    number = number + 1;  // 1 added to number locally, and is referencing inside method only.


}
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • Thanks to all three for clearing it up for me.Now I understand the concept. I was confused because, earlier I was told that the value of a variable "can" change in the flow of a program when the same variable is assigned a different value later. – Jboy Feb 06 '15 at 08:15