Java : could not find or load main class error in vs code while running a file inside package

Java : could not find or load main class error in vs code while running a file inside package

Making Packages in Java

The package in java is used to group related classes , In other IDE's like IntelliJ Idea and Eclipse , they have build in environment for java development not as the VS code.

How to make package in VS Code ?

You just need to make a directory inside your source folder and move the related classes inside that directory. You will notice the vs code will automatically add a line of code Package Packagename; on the first line of the code that line declares that this class is inside a package called Packagename.

What if you directly run the code now ?

If you run the code directly in VS Code , lets run it by doing javac filename.java then java classname

just take a look at the above picture the java file is compiled successfully, Now lets try to run it with java classname

As we can see running this file gives an error that is Could not find or load main class classname .

How to resolve this error ?

This is a common error occurs when we try to directly execute the class , but execution of java class inside package is slightly different from executing a normal java class , Java says that if the file is inside a package, so you first need to compile it being inside that package and then execute the file by jumping to the root folder of that package and then executive it as java packagename.classname.

You can see it is working and executing perfectly fine.