Compiling Java sources won’t produce executable which could be run independently. It produces binary code which is executed by Java. So in order to run Java program you need Java to be installed. Just to run a Java application JRE (Java Runtime Environment) should be enough. If you want to write Java application you will need JDK (Java Development Kit).
To install JRE on Linux with apt-get run
sudo apt-get install defaulf-jre
To install JDK on Linux with apt-get run
sudo apt-get install defaulf-jdk
To install JRE on Linux with yum run
sudo yum install java-1.8.0-openjdk
To install JDK on Linux with yum run
sudo yum install java-1.8.0-openjdk-devel
To install JRE/JDK on Windows go here. Please note that if you are installing JDK there is no need to install JRE; JDK comes with everything you need. Also I would recommend to add jdk/bin path to the system path (Control Panel -> System -> Advances system settings -> Environment Variables -> System variables -> Path)
To verify run in command prompt
java
javac
for both commands you should see Usage:… help.
Now let’s do a Hello World:
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World from Java");
}
}
save it as HelloWorld.java and to compile it run:
javac HelloWorld.java
to run:
java HelloWorld.class
Way too easy, isn’t it? In real life it’s a little bit more complicated than that.
First of all none has source files just lying around, everything is organized in what in Java called packages.
So let’s do it.
– create folder java1
– inside java1 one create folders src and classes
– and inside java1/src create folder ak
– create new file in java1/src/ak HelloWorld.java
package ak;
class HelloWorld
{
public static void main(String args[])
{
System.out.println("Hello World from Java");
}
}
please note that we added package name at the beginning of the file.
to compile it run:
javac -sourcepath src -d classes src/ak/HelloWorld.java
to run:
java -cp classes ak.HelloWorld
for the compiler we indicated where source file are and which folder to put class files
for the Java we indicated where classes are located and which is main class
And the last step. None deploys class files to a customer. Java application are usually distributed in jar files.
Let’s create a jar file:
jar cfv out/HelloWorld.jar -C classes .
to run
java -cp out/HelloWorld.jar ak.HelloWorld
for the Java we indicated where classes are located and which is main class
But we could simplify things by indicating which is the main class right inside jar file, we do it by creating what’s called manifest file:
echo Main-Class: ak.HelloWorld>manifest.mf
on Windows just create file manifest.mf
Manifest-version: 1.0
Main-Class: ak.HelloWorld
and now create new jar file
jar cfmv out/HelloWorld.jar manifest.mf -C classes .
and to run
java -jar out/HelloWorld.jar
notice that all we have to do is indicate jar file.