Monday, November 19, 2007

Saying Hello (cliched, but effective)

Without much ado, let us get our first java program going. I'm going to assume here that you'll just blindly key in the programs given below without jumping the gun and getting too curious (beacuase curiousity killed the cat). From now on, things are going to be less theoretical. Our first program is going to have two flavours. You can try them out and see the difference.
Any program in this book would start with the name of the program file and a number prefixed by P. So our first program , has it's title as P1: HelloJava.java:

P1 : HelloJava.java

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

P2 : HelloJavaWindow.java

import javax.swing.*;

public class HelloJavaWindow {
public static void main(String args[]){
JFrame jfHello=new JFrame("Hello Java Window");
jfHello.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfHello.setSize(300,400);
jfHello.setVisible(true);
}
}

Any procedure will be a paragraph with a heading prefixed by PR and will have a number and a short name describind what we do in that procedure. So, we have our first procedure PR1 below:

PR 1: Compiling HelloJava program
Have you tried compiling P1 and P2 ? Be sure that P1's filename is as I have mentioned: "HelloJava.java". Create a file HelloJava.java with the program in P1 above as it's content. To compile P1, type in "javac HelloJava.java" from the command line window (or terminal in Linux) after navigating it to the directory where you have the file HelloJava.java. this should create a file called HelloJava.class in the same directory.To execute this, type "java HelloJava" (and not java HelloJava.class or java hellojava) in the same command window. You should see the text "Hello Java" printed on screen.

Repeat the PR1 and read "HelloJavaWindow" for HelloJava and P2 for P1. What output do you see now, on running "java HelloJavaWindow" ?

Next Section >> Explanation of the hello java program