Simple java programs for beginners

    
  We begin with a very simple program that prints a line of text as output.


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



is perhaps the simplest of all Java programs. Nevertheless, it brings out some salient features
f the language. Let us therefore discuss the program line by line and understand the unique features that constitute a Java program.


Class Declaration

 The first line
                 class SampleOne

declares a class, which is an object-oriented construct. As stated earlier Java is a true object-orient
language and therefore, everything must be placed inside a class. class is a keyword and declares that 
new class definition follows. SampleOne is a Java identifier that specifies the name of the class to be defined.

Opening Brace

Every class definition in Java begins with an opening brace "{" and ends with a matching closing brace "}" , appearing in the last line in the example. This is similar to C++ class construct. (Note that a class definition  in C++ ends with a semicolon.)

The Main Line


The third line
                    public static void main (String args[ ])

defines a method named main. Conceptually, this is similar to the main( ) function in C/C++. Every Java application program must include the main() method. This is the starting point for the interpreter to be the execution of the program. A Java application can have any number of classes but only one of them must include a main method to initiate the execution. (Note that Java applets will not use the main method at all.)
This line contains a number of keywords, public, static and void.

Public :
         The keyword public is at access specifier that declares the main method as unprotected and       therefore making it accessible to all other classes This is similar to the C++ public modifier,

Static:
          next appears the keyword static, which declares this method as one that belongs to the entire class and not a port of any objects of the class. The main must always be declared as static since the interpreter uses this method before any objects are created. More about static methods and variables 
will be discussed later.

Void:
       The type modifier void states that the main method does not return any value (but simply pr
ints some  to the screen.)
All parameters to a method are declared inside a pair of parentheses, Here, String args[] declares a
parameter named args, which contains an array of objects of the class type String




No comments:

Post a Comment