Friday, 1 June 2012

The first Java Program

The first Java Program



A basic java program consists of a class name, and a main method. The following program is simple the first program for any language, the Hello World program. It consists of a class name called "HelloWorld" and a main method :
"public static void main(String[] args)"
 This is the method that gets executed when the program is run, details will follow later. What the program does is that it simply prints the word "Hello World!" to the console.

The statement for printing this line is :
System.out.println("Hello World!");

So what ever you put in the brackets will be printed to the console. This is the java program here :

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

The program must be saved as ClassName.java , this is important, otherwise the code will not compile.


Now to see if u are familiar with it, play around with the text in the brackets, keep changing it and keep compiling and running the code to see the results, we will move on to the next step on the next post.

PS:
*All java classes must begin with an upper case letter
*The filename of your code must match the classname, eg, if u have public class HelloWorld , you must save the file as HelloWorld.java
 *If the classname consists of two words like Hello World, each word must begin with an upper case letter
  like this HelloWorld
*there should be no spaces between the words making a class name

Compiling :
linux  - javac HelloWorld.java
        - java HelloWorld

IntelliJ - ctrl + shift + F10 = make: it will compile and run the code
          - ctrl _ shift + F9 will just compile..

goodluck!

For more info, like our facebook page at https://www.facebook.com/ssutradhar35 and join our group at https://www.facebook.com/groups/computerkorner/

3 comments:

Unknown said...

Just to add to the above explanation... For beginners.. after writing the program, you must save it with *.java extension.

and the java filename must match the name of the class.

Ex:

public class HelloWorld
{
// Java Statements
}

You must save it as HelloWorld.java

And then after saving, while compiling it with CLI.

$ javac HeloWorld.java
(after compilation is successful)

$ java HelloWorld

Thanks

Parag said...

NOTE : its not compulsory to have name of the file same as that of the class name. u can give any other name also. so for compiling u may write " javac filename.java" . and while running the program "java name_of_class"..

Unknown said...

where is the reaming lecture and topic

Post a Comment