Tuesday, April 28, 2015

Hello world in Java

Is Java Development Kit installed on your machine?

The path of the JDK (for Windows) by default is the following:

C:\Program Files\Java\jdk<version>

If the above directory is not present, there is a good chance JDK is not installed on your machine (you may want to search for it). Download and install the JDK from Oracle's website (for Windows it is available as an exe installer).

(After installation, you have to set the PATH environment variable in Windows. That is not discussed here. For this, you may refer to any source on the Web. The configuration process differs for each OS.)

When you have done that, open the console and type the following commands:

 C:\Users\Utsav>javac -version  
 javac 1.7.0_71
  
 C:\Users\Utsav>java -version  
 java version "1.7.0_71"  
 Java(TM) SE Runtime Environment (build 1.7.0_71-b14)  
 Java HotSpot(TM) Client VM (build 24.71-b01, mixed mode, sharing)
  
 C:\Users\Utsav>  

If you see the above (or slightly differing) output, you have the JDK set up to begin development.

"Hello world!" in Java

Open the notepad (or your favorite text editor) and type the following program:

 public class HelloWorld {  
   
     public static void main(String[] args) {  
         System.out.println("Hello world!");  
     }  
   
 }  
   

Don't worry about the details for now. Save the file as HelloWorld.java (note the .java extension). Open the console and change to the directory containing the above file.

Run the following command:

 D:\Dropbox\practice\blog>javac HelloWorld.java  
   
 D:\Dropbox\practice\blog>  

If the command executes successfully as seen above, it means you have compiled the code and it is ready to be run by the JVM (more on that later). A file with the name HelloWorld.class must have been created in the same directory.

Now run the following command:

 D:\Dropbox\practice\blog>java HelloWorld  
 Hello world!  
   
 D:\Dropbox\practice\blog>  

The output is "Hello world!" as seen above. Congratulations! You have said "Hello world!" in Java. Feel free to experiment further until you feel ready to move ahead.

No comments :

Post a Comment