Wednesday, June 23, 2010

How to run a Java program in Linux

Java (JDK) installation:
Download the latest jdk from sun's website http://java.sun.com/javase/downloads/index.jsp
e.g.; 
jdk-6u20-linux-i586.bin

now make this bin file executable.
chmod +x jdk-6u20-linux-i586.bin
To execute the bin file, type
./jdk-6u20-linux-i586.bin
Agree the License agreement. It will extract the content of bin file into a directory named jdk1.6.0_20
rename this directory to jdk1.6
mv  jdk1.6.0_20  jdk1.6
Now move this directory to /usr/share/
sudo mv jdk1.6 /usr/share/
set path to the java bin directory
export PATH=$PATH:/usr/share/jdk1.6/bin
or make it permanent in .bashrc file of your user's home directory
vim .bashrc
export PATH=$PATH:/usr/share/jdk1.6/bin
save and close this file
reread .bashrc file using source command
source .bashrc
Write a program in java: 
Open your favorite editor in Linux. Type a sample Hello world program 
/*
java Hello World example.
*/
class HelloWorldExample 
{ 
public static void main(String args[]) 
{ 
/* 
Use System.out.println() to print on console. 
*/ 
System.out.println("Hello World !"); 
} 
} 
/* 
OUTPUT of the above given Java Hello World Example would be : 
Hello World ! 
*/ 
Save it as HelloWorldExample.java
Now compile it
javac HelloWorldExample.java
it will create a file named HelloWorldExample.class. Now you can run the HelloWorldExample.class file.
java HelloWorldExample
*** Important!!!!! this is HelloWorldExample not HelloWorldExample.class

  
   

No comments:

Post a Comment