1

The output of this program is 5. Why is that the case? Why isn't the output 6? How to write a method that will actually add value to x? Thanks.

public static void main (String args []) {
            
    int x = 5;
    example (x);
    System.out.println(x);
            
}
            
public static void example (int x) {
                
    x = x + 1;
                
}
Pentium1080Ti
  • 1,040
  • 1
  • 7
  • 16
  • 3
    These are two different `x` in different scopes – Marged Jan 09 '21 at 23:14
  • 1
    Incrementing x inside the method doesn't change the original x. You need to learn about variable scope. – NomadMaker Jan 09 '21 at 23:24
  • In java everything is passed by value, but Objects references in Java are pointers, so when an Object is passed by value, the content of the Object pointed will change. – Israel Figueirido Jan 09 '21 at 23:36
  • When you use primitive (int, long, etc..) like method parameters, you pass the variables like values, and it going to assign the value to your primitive parameter, and it going to be two differ variables with the same value at first, changes in one will no affect the other. When you use Object (Integer, String, etc..) like parameters, you are passing the reference of the object, you going to have 2 variables pointing to the same memory location, so changes in one will reflect in the other one. – Marcos Echagüe Jan 09 '21 at 23:38

1 Answers1

1

There are 2 solutions to this:

  1. return the new x
public class Main {
    public static void main (String args []) {
      int x = 5;
      x = example(x);
      System.out.println(x);
    }
    public static int example(int x) {
          return x + 1;
    }
}
  1. Store x as a class variable
public class Main {
    static int x;

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

I recommend approach 1.

Coder
  • 1,175
  • 1
  • 12
  • 32