Calling a method from another class stops at that statement

1.2k Views Asked by At

I do not really understand what is going on with my program. I call a method from [another class] and somehow [the class that called the method] stops working where the call was made and doesnt execute the rest of the program.

No errors popped up either, it simply just didnt run the rest (Checked with print statements)

Here is my code :

Class that calls the method

Banana ban = new Banana();
String[] listOfBananas = ban.getBananas(); //Stops at this statement
//Below is a check that never gets executed as with the rest of the program
System.out.println("I didnt get to this statement");

//Do other stuff with the array...

Class that has the method

public class Banana {
    public static String[] giveOtherClassList;

    public Banana(){
    }

    public static void main(String[] args) {
        StringBuilder a = new StringBuilder();
        a.append("text text1 text2 text3");
        giveOtherClassList = a.toString().split(" "); //Split will create an array
    }

    public String[] getBananas() {
        //I know this method works because I ran this program with
        //giveOtherClassList[3] and it returned the correct value
        return giveOtherClassList;
    }
}
1

There are 1 best solutions below

3
On BEST ANSWER

Given the code you provided, I am pretty sure the main method within Banana gets executed instead of the code you actually want to execute. Just remove the main method within Banana and rerun the test. To be sure: add System.out.println("Start"); as the first line within your main.

Here is a MWE just for documentation purpose:

public class Main implements Foo {
    public static void main(String... args) {
        Banana ban = new Banana();
        String[] listOfBananas = ban.getBananas();
        System.out.println("I didnt get to this statement");
    }
}

class Banana {
    public static String[] giveOtherClassList;

    public Banana() {
    }

    public String[] getBananas() {
        return giveOtherClassList;
    }
}

This program produces the output I didnt get to this statement, which - clearly - is not true and therefore the program works :)