Call an array from one method to another method [closed]

Here’s a text (comment) illustrated explanation (both the question and the answer):

public Object[] methodA() {
    // We are method A
    // In which we create an array
    Object[] someArrayCreatedInMethodA = new Object[10];
    // And we can returned someArrayCreatedInMethodA
    return someArrayCreatedInMethodA;
}

public void methodB() {
    // Here we are inside another method B
    // And we want to use the array
    // And there is a possibility that we can call the method A inside method B
    Object[] someArrayCreatedAndReturnedByMethodA = methodA();
    // And we have the array created in method A
    // And we can use it here (in method B)
    // Without creating it in method B again
}

Edit:

You edited your question and included your code. In your code the array is not created in method A but in the myArray(), and you don’t return it, so it is “lost” after the myArray() method returns (if it is ever called).

Suggestion: declare your array as an attribute of your class, make it static, and you can simply refer to it as resultCard from both methods a() and b():

private static String[][] resultCard = new String[][] {
    { " ", "A", "B", "C"},
    { "Maths", "78", "98","55"},
    { "Physics", "55", "65", "88"},
    { "Java", "73", "66", "69"},
};

public static void A() {
    // "Not sure how I can include the array (myArray) here"
    // You can access it and work with it simply by using its name:
    System.out.println(resultCard[3][0]); // Prints "Java"
    resultCard[3][0] = "Easy";
    System.out.println(resultCard[3][0]); // Prints "Easy"
}

Leave a Comment