Search code examples
javaclassmethodsintegerdeclare

Is it possible to link integers from a method to a class?


I have a quick question out of curiosity...if I declare an integer in one method, for example: i = 1, is it possible for me to take that i and use its value in my main class (or another method)? The following code may be helpful in understanding what I'm asking...of course, the code might not be correct depending on what the answer is.

public class main {
  public main() {
    int n = 1;
    System.out.print(n + i);
  }

  public number(){
    i = 1;
  }
}

Solution

  • You may use a class-scope field to store you variable in a class object or you can return it from one method or pass it as a parameter to the other. Mind that you will need to call your methods in the right order, which is not the best design possible.

    public class main {
    
      int n;
      int i;
      public main() {
        n = 1;
        System.out.print(n + i);
      }
    
      public number(){
        i = 1;
      }
    }