Quatsch
Quatsch

Reputation: 392

Create array in method and use it in another method

I want to use an array in a method that got created in another method of the same class.

  public class Class1 {
    public static String[] method1() {
      String[] array = new String[5];
      array[0] = "test";
      return array;
    }

    public void method2() {
      System.out.println(array[0]);
    }
   }

Upvotes: 2

Views: 139

Answers (3)

Santiago Benoit
Santiago Benoit

Reputation: 994

Simply declare it outside of your methods, like this: String[] array;

So, your code would look like this:

public class Class1 {


public static String[] method1() {
    array = new String[5];
    array[0] = "test";
    return array;
}

public static void main(String[] args) {
    System.out.println(Arrays.toString(method1())); // Converts array to string
}
static String[] array; // Declaring global variable

}

The output should look like this: [test, null, null, null, null]

Upvotes: 0

user3487063
user3487063

Reputation: 3682

can do it like below for example:

public class Class1 {
    public static String[] method1() {
      String[] array = new String[5];
      array[0] = "test";
      return array;
    }

    public void method2(String[] array) {
      System.out.println(array[0]);
    }
public static void main(String[] args){
Class1 obj = new Class1();
obj.method2(method1());
}
       }

or call the method in method2

 public class Class1 {
        public static String[] method1() {
          String[] array = new String[5];
          array[0] = "test";
          return array;
        }

        public void method2() {
String[] array = Class1.method1();
          System.out.println(array[0]);
        }
public static void main(String[] args){
    Class1 obj = new Class1();
    obj.method2();
    }
           }

Upvotes: 1

Jason Lee
Jason Lee

Reputation: 71

The array in the method1 is just a local variable, so it cannot be used in class2 directly. If you want to use that "array", you can just invoke method1(). And it returns the array, then you can use it. e.g.

String[] array2 = method1();
System.out.println(array2[0]);

Upvotes: 1

Related Questions