-2

Given this code:

public class Test {

  public void add(int x){
    x++;
  }

  public static void main(String args[]){
    Test t = new Test();
    int a = 1;
    t.add(a);
    System.out.println(a);
  }
}

I just want to print out 2 instead of 1. I think I am calling this method wrong. Could you help me understand why?

David
  • 2,987
  • 1
  • 29
  • 35
UZI
  • 1

3 Answers3

1

java passes by value , that means your variable got serialized and its value was sent to the method.

To print 2 you need to make your method returns the value after increment .

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43
1

Your method is declared void so it doesn't return anything. Variable a will always remain unchanged when using it for calling the method add.

It should be, for your purpose:

public int add(int x){
   return x++;
}
sinclair
  • 2,812
  • 4
  • 24
  • 53
Dez
  • 5,702
  • 8
  • 42
  • 51
1

There are a lot of errors in your code, and you should study Java properly. It shows you haven't understand neither the unary operators, that's not strictly related to Java.

However one of the possible solutions (there are many), is to change your code as follow:

public class Test {

  public int add(int x){
    return ++x;
  }

  public static void main(String args[]){
    Test t = new Test();
    int a = 1;
    a = t.add(a);
    System.out.println(a);
  }

}

Again, study properly Java before trying any exercise or posting on SO. Next time, before posting a new question please review how to ask.

Community
  • 1
  • 1
David
  • 2,987
  • 1
  • 29
  • 35