Does a .jar file need all of the classes installed on a machine to run? For example: if I ever distribute a program as a .jar file, will I also need to install all my .class files on the user's machine? If so, is there a way to distribute a java program as one file (such as an executable)?
-
Based on a comment in an answer: _why do I get this message: Error: Could not find or load main class Server Caused by: java.lang.ClassNotFoundException: Server_, this question has been asked a lot on SO: [How to fix `ClassNotFoundException`?](https://stackoverflow.com/search?q=[java]+how+to+fix+ClassNotFoundException) Does [this](https://stackoverflow.com/questions/17408769/how-do-i-resolve-classnotfoundexception) help as a starting point? Otherwise, more details about how you are building and running your program may be needed. – andrewJames Aug 30 '20 at 23:42
3 Answers
It depends on how you built the jar. Classes in your jar can depend on other classes in your jar, and/or on classes in other jars installed on your system. In the later case, they probably won't work if you distribute the jar to other users.
You need to ensure that the jar you build and distribute contains all dependencies you are using. I've heard that Maven can help here.

- 37,781
- 10
- 100
- 107
The classes are compiled into the .jar file, so you do not have to install them on every machine. And yes there is a way to distribute an executable .jar file.

- 33
- 4
-
If the classes are compiled into a .jar file, then why do I get this message: ```Error: Could not find or load main class Server Caused by: java.lang.ClassNotFoundException: Server``` Whenever I run a.jar file with the class Server in a different folder? – Serket Aug 30 '20 at 23:27
-
If you get the `java.lang.ClassNotFoundException` error, the class is most likely missing in your .classpath file. – scaldings Aug 30 '20 at 23:34
-
I've asked a new question regarding this issue. Here is the link: https://stackoverflow.com/questions/63663114/running-jar-file-returns-error-error-could-not-find-or-load-main-class-myclass – Serket Aug 30 '20 at 23:42
In fact a .jar file is an excutable. You can execute it with java -jar jarFile
.
Whether you jar contains all classes to run the jar depends on how you built it.
You can pack all denpendencies in you jar which is called a fat jar, or you can just declare your dependencies and just pack you own class in the jar with build tools like maven or gradle. In the later way the user can download the dependency with the same build tool. Usually the later way is better.

- 1,241
- 4
- 17
-
Only if the manifest contains a [`Main-Class`](https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html) entry – René Link Aug 31 '20 at 03:50