«Could not find or load main class» Error while running java program using cmd prompt [duplicate]
I am running a simple «HelloWorld» Program. I get this error in the command prompt:
My sample program looks like this:
15 Answers 15
When the Main class is inside a package then you need to run it as follows :
In your case you should run the program as follows :
What’s your CLASSPATH value?
It may look like this:
Now, you’re in path D:\myjavatest\ on the CMD line.
Type this to compile it:
Then, type this to run it:
You may get what you want.
So I moved back to the main directory and executed:
Since you’re running it from command prompt, you need to make sure your classpath is correct. If you set it already, you need to restart your terminal to re-load your system variables.
You can check your classpath, by printing CLASSPATH variable:
I had the same problem, mine was a little different though I did not have a package name. My problem was the Class Path for example:
When you add a new environment setting you need to reboot before enabling the variable. But from the command prompt you can set it. It also can be set like I mentioned at the beginning. For more info, and if your using a different OS, check: Environment Variables.
One reason for this error might be
Could not find or load main class
Maybe you use your class name as different name and save the class name with another name you can save a java source file name by another name than class name. For example:
you can save as Hello.java but,
To Compile : javac Hello.java
This will auto generate A.class file at same location.
Now To Run : java A
This command works when you have declared package.
. represent current directory/.
I had a similar problem when running java on win10
I was getting the exact same error for forgetting to remove the .class extension when running the JAVA class. So instead of this:
One should do this:
Removing the unpacked jar which contained the manifest fixed it.
faced the same problem. solved by following these steps
For a lot of us, at least for me, I think the class path hierarchy is not intuitive since I’m working inside a directory structure and it feels like that ought to be it.
Java is looking at the name of the class based on it’s package path, not just the file path.
The command «java packagefoo.MainClass» is running off the root %CLASSPATH% which means something significant to Java. Then from there it traverses package names, not path names like us lay coders would expect.
So if my CLASSPATH is set to %CWD%/, then «java packagefoo.MainClass» will work. If I set the CLASSPATH to %CWD%/packagefoo/ then packagefoo.MainClass can’t be found. Always «java MainClass» means nothing, if it is a member of «package», until I rip out the java code «package packagefoo;» and move the Class File up a directory.
In fact if I change «package packagefoo;» to «package foopackage;» I have to create a subfolder under CLASSPATH/foopackage or foopackage.MainClass stops working again.
To make matters worse, Between PATH, CLASSPATH, JAVAHOME, for Windows, JDeveloper, Oracle Database, and every user name it was installed under, I think a coder trying to just get something up fast ends up brute forcing path variables and structure until something works without understanding what it means.
Error: Could not find or load main class [duplicate]
I am having trouble compiling and running my Java code, intended to allow me to interface Java with a shared object for Vensim, a simulation modeling package.
The following code compiles without error:
However, when I try to run the following:
22 Answers 22
If the class is in a package
Finally, note that the compiled (.class) version is executed, not the source code (.java) version. Hence “CLASSPATH.”
You can try these two when you are getting the error: ‘could not find or load main class’
If your class file is saved in following directory with HelloWorld program name d:\sample
I believe you need to add the current directory to the Java classpath
You have to include classpath to your javac and java commands
suppose you have the following
Package Named: com.test Class Name: Hello (Having main) file is located inside «src/com/test/Hello.java»
from outside directory:
If you work in Eclipse, just make a cleanup ( project\clean.. clean all projects ) of the project.
You have to set the classpath if you get the error:
Could not find or load main class XYZ
I got this error because I was trying to run
Because it simply never included your class in the packaged Jar.
Could not find or load main class with a Jar File
I’m trying to load a jar using
With the manifest of
In the Jar directory, I can clearly see a classes\TestClass file when I extract it.
Package Deceleration in classes.TestClass is package classes;
But I still keep getting the error message
I’ve been through everything I’ve been able to find with this problem, and none of it seems to help.
I’ve tried editing the classpath, redoing the manifest, installing the new JRE.
What else should I be doing?
18 Answers 18
I got it working like this:
TestClass.Java
MANIFEST.MF
to run any other class having «public static void main» in some package,
This error comes even if you miss «-» by mistake before the word jar
Wrong command java jar test.jar
1.Create a text file calles Manifest.txt and provide the value as
2.Create the jar as
jar cfm test.jar Manifest.txt classes/*.class
I know this is an old question, but I had this problem recently and none of the answers helped me. However, Corral’s comment on Ryan Atkinson’s answer did tip me off to the problem.
Почему не запускается код на Java?
Пробую изучать программирование. Подскажите, почему код на java не запускается.
Читаю книгу Сьерра, Бейтс «Изучаем Java» и захотел уже опробовать код. Дочитал до 70-ой страницы, но пока все в теории и без запуска. В книге нет инструкции по установке и настройке Java, но знакомый подсказал создать переменные в свойствах системы.
public static void main(String[] args) <
В командной строке:
Error: Could not find or load main class HelloWorld
Файл с бинарным кодом HelloWorld.class на диске C появляется.
Java 7 64bit стоит в D:\Program Files\Java. Система Windows 7 64bit
Заранее спасибо за помощь!
P.S. Честно говоря, ожидал, что при изучении современных языков увижу среду разработки по типу Delphi, Visual Studio. А тут такой хардкорд в виде командной консоли.
Я создал перед запуском такие переменные:
JAVA_HOME=D:\Program Files\Java\jdk1.7.0_25
CLASSPATH=D:\Program Files\Java\jdk1.7.0_25;D:\Program Files\Java\jdk1.7.0_25\LIB
PATH=D:\Program Files\Java\jdk1.7.0_25\;D:\Program Files\Java\jdk1.7.0_25\LIB;D:\Program Files\Java\jdk1.7.0_25\BIN
без пробелов перед «;» и перезагрузил ПК.
Как я понимаю, в «CLASSPATH» нужно дописать и диск Ц (а лучше папку на нем создать и ее прописать), потому что он также содержит классы?
Как это все трудно понимать дизайнеру. В книге про настройку среды всего 1 предложение и то, вроде, команда Линукса. %(
Скопировал файл в D:\Program Files\Java\jdk1.7.0_25;D:\Program Files\Java\jdk1.7.0_25\LIB Запустился без ошибок. Потом создам на диске С каталог, чтобы далеко не бегать в командной строке, и добавлю в переменную.
Я думал, что здесь как в Фотошоп: есть привязка типа файлов и они запускаются из любого места. Меня очень удивило, что компилируется он без ошибок, но не запускается.
Добрый день. Специально зарегестрировался, чтобы описать решение этой проблемы.
Сам недели две назад тоже мучился и думал что я м.д.к, потому ничего не работает.
Это не совсем так, поэтому читайте ниже.
Суть проблемы:
При повторение видео урока, а точнее действий в нем, желаемый результат не выводился. Конкретнее была написана программа вывода сообщения Hellow World в консоли WIndows
А именно, компилированный ява файл, вызывался командой java ИМЯ.class, и выходила соответствующая ошибка: «could not find or load main class ИМЯ_класса»
т
Как решил:
Вызывать надо уже ОТКОМПИЛИРОВАННЫЙ файл командой[b][i] java ИМЯ [/i][/b]И все. Тогда консоль нормально воспроизводит программу, если, разумеется, в ней нет ошибок.
Возможно для гуру программирования, это очевидный ответ, и кажется что это норма, но я как 3-ью неделю изучающий яву, на второй день реально не понимал в чем суть проблемы. И так как несмотря на то что обучение идет трудно, мне было обидно и непонятно почему это не работает.
Ниже распишу полный алгоритм работы с ява машиной на базовом уровне, может быть кому-то это поможет.
1) Скачать JDK c оф сайта (ссылку давать не буду, это точно найти сможете)
2) Установить скачанный пакет
3) Подключить установленную ява машину к нашей системе ( у меня это Windows 7)
а) зайти в папку с установленным пакетом и найти файл java.exe (у меня на Windows это было: C:\Program Files\Java\jdk1.8.0_05\bin\java.exe)
_______обращаю внимание, что находить именно файл java.exe не обязательно, просто я сделал так=)
б) Нажать на java.exe правой кнопкой мыши, выбрать «Свойства». В выскочевшем окошке, во вкладке «Общие», ищите строку «Расположение». Выделяйте и копируйте путь (у меня это C:\Program Files\Java\jdk1.8.0_05\bin)
в) Открываем пуск, наводим мышку на «Мой компьютер», жмем правую кнопку мыши, жмем «Свойства».
г) В открывшемся окне, слева, жмем кнопку «Дополнительный параметры системы»
д) В отрывшемся окне «Свойства системы», во вкладке «Дополнительно» (она по умолчанию выделена/открыта), внизу ищем кнопку «Переменные среды». Жмем на нее
е) В открывшемся окне «Переменные среды», в верхней его части, а именно «Переменная среды пользователя. » нажимаем кнопку создать
ж) В открывшемся окне вводим имя переменной, у меня это Path (можно ли другую, я не знаю), а в поле «Значение» вводим наш скопированный путь (C:\Program Files\Java\jdk1.8.0_05\bin)
д) Жмем «ОК», сохраняем все.
4) Проверяем нашу ява машину
а) Запускаем консоль (либо WIN + r => затем cmd и Enter либо Пуск => вводим в поиск над пуском cmd и жмем Enter)
б) В открывшейся консоли, вводим java
в) После этого должно появиться куча команд ява, служебная информция и прочее, если все нормально подключилось, если нет, то выдаст ошибку, вроде «Нет такой команды», или что-то похожее. Если что-то не так, делай действия выше по новой.
5)Если все ок, идем дальше. Создаем нашу простую программу на java.
6)Открываем блокнот, и пишем там код ниже:
[code=java]public class Hellow
<
public static void main(String[] args)
<
System.out.println(«Hellow World!»);
13) в консоли, на новой строке, выскочит сообщение Hellow World!
Все.
Вот собственно алгоритм запуска ява программ из консоил виндоус.
Я не претендую на полноту изложения, убер крутой и новый материал, просто я две недели сам мучился с этой проблемой, и писал код в среде разработчика IDEA. И мучался тем, что имея уже какое-то представление о Java, не мог запустить ее через консоль. Меня это мучило, поэтому когда я смотря очередную лекцию, увидел в чем была моя ошибка, меня осенило, и я решил свою проблемы, сняв камень с души, и как следствие, успокоившись. На радостях, я решил, что если в мире есть хотя бы еще один человек, которому эта информация может помочь, то пусть будет так.
Спасибо за внимание и заранее извините за ошибки. Если когда-нибудь надо будет, может быть я исправлю все недочеты своей короткой статьи, а пока держите, как есть.
Удачи в программировании!
Error: Could not find or load main class in intelliJ IDE
I’m a beginner in Java and am trying to run my code using IntelliJ that I just installed as my IDE with JDK 1.7. The following piece of code keeps does not even compile and keeps giving me the error:
Is there any change that i have to make in the compiler settings?? Or is it the code.
45 Answers 45
If none of the above answers worked for you, just close your IntelliJ IDE and remove the IntelliJ IDE file and folder from the root of your project:
Then open the project with IntelliJ. It must work now.
For me the solution was to fix the output directory under project settings. Before I was using just «target» for the Project compiler output. Instead I updated it to have a full path e.g. D:\dev\sigplusjava2_68\target
I had this problem and I tried everything under the sun that I could think of and on this site.
None of my Java classes were being picked up after I pulled from a remote branch. All the classes had red Js by their names in the Project Hierarchy, not blue Cs.
In the end, I tried to follow this tutorial and a few steps in tried something not described and fixed the issue: https://www.jetbrains.com/help/idea/creating-and-managing-modules.html
For some reason, all my classes then had blue C’s.
Someone with a better understanding of how IntelliJ and/or IDE’s might be able to explain the phenomenon, but all I know is now it can see all the classes and more importantly the main one, and run.
Invalidate cache and restart your IntelliJ, it worked for me.
Explicitly creating an out folder and then setting the output path to C:\Users\USERNAME\IdeaProjects\PROJECTNAME\out
Also try having IntelliJ make you a new run configuration:
Find the previous one by clicking
Now, (IMPORTANT STEP) open the class containing your main method. This is probably easiest done by clicking on the class name in the left-hand side Project Pane.
Give ‘er a Alt + Shift + F10 and you should get a
I know this was asked a while ago, but I was just stumbling over this issue and thought my findings might help others. As pointed out, the error message is basically a result of the out folder. That’s because, when you’re trying to run the program, it compiles the code first, and puts the compiled result to the out location, and then it tries to load the compiled code from the out location. If the compiled code is not in the location expected, you’ll get the error.
The point I’m particularly wanting to share is that some times, the code is not compiled (built), even though your run configuration specifies «Build» in the «Before launch» section of the configuration panel.
When can this happen? One situation that can cause this to happen is if you’re using modules and you manually delete the module out directory. For example, if I have a module named «foo», there should be a directory named foo under out/production. If you manually delete it, the build system may not know that it needs to be rebuilt.
Even worse, if you select Build | Build module ‘foo’, it still may not rebuild the module. If that’s the case, you should select a file in the module, for example ‘bar.java’ and then select Build | Recompile ‘bar.java’. Now the out directory out/production/foo should be restored.
Since IntelliJ typically knows about any changes going on, this surprised me, and took me a little time to figure out, so I thought I’d share.



























