Main method not found in class com.codewithmosh.Array

Course: The Ultimate Data Structures & Algorithms: Part 1
Topic: Arrays
Lecture: 5- Solution- Creating the Class

I was following the video for creating an array class but keep stumbling into the following error:

"Error: Main method not found in class com.codewithmosh.Array, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application"

I found a couple of sources saying that Java requires a main method as an entry point to an application. However, there is no main method in the tutorial video or in the source code posted by Mosh. I have posted the code I have so far below, any help would be appreciated.

Array class:

package com.codewithmosh;

public class Array {
    private int[] items;

    public Array(int length) {
        items = new int[length];
    }

    public void print() {
        for (int i = 0; i < items.length; i++)
            System.out.println(items[i]);
    }
}

Main class:

package com.codewithmosh;

public class Main {
    public static void main(String[] args){
        Array numbers = new Array(3);
        numbers.print();
    }
}

Seems like you’re trying to run the Array class. Run Main instead.

1 Like

You were absolutely correct. Thank you very much.

In Java, each application must have the main method. The main method is the entry point of every java program. The java program searches for the main method while running. This error occurred when the main method is not available. The reason that the compiler don’t complain about the public is because it doesn’t care about the main method. It doesn’t take difference for it if a main exists or not. It’s the JVM which need a start point public and static to launch your application.

So you should make your main method as public:

public static void main(String[] args)

The JVM is programmed to look for a specific signature for the main method before executing the program. It finds this signature by looking for a specific series of bytes in the bytecode. That signature only results from compiling a method that is - public static void main. If any of the three modifiers (public, static and void) are omitted the bytecode code will look different and the JVM will not be able to find your main method.