2

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]);
    }
   }
3
  • 2
    Pass it as an argument, store it in a field, etc. Commented Aug 20, 2014 at 2:08
  • Call the method and get the array. Or call method that will store in a field you can access that field Commented Aug 20, 2014 at 2:09
  • Could you please write that in an example code? My brain is very exhausted and I can't figure it out right now. Commented Aug 20, 2014 at 2:12

3 Answers 3

1

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();
    }
           }
Sign up to request clarification or add additional context in comments.

Comments

1

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]);

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.