-1

I learned static method today, and I am confused about how values change inside the static method. When I write static method like this

public class test{
public static int printInt(int t,int n){
System.out.println(t);
t= t + n;
return n;
}
}

and call it in main

public class Method {
public static int i;
public static int m;
public static void main(String[] args){
    i = 5;
    m = 6;

    test.printInt(i,m);
    System.out.println(i);
}
}

the t do not change as I suppose to. If the static method only make change into values that you return?

ksdawq
  • 29
  • 1
  • 5

1 Answers1

0

The term static in simplest terms denotes something that belongs to the class. In the above code method printInt belongs to the class test and not to a specific instance of this class.

In the main method which is in another class Method you are trying to pass local variables i and m as parameters and due to that copy of them will be passed to method printInt. You make changes to copy and not actual arguments. So changes will not be reflected in the main method.

Note: Use camel-case and other standard coding conventions in Java. Also naming a class Method is a bad idea.

akhil_mittal
  • 23,309
  • 7
  • 96
  • 95