Wednesday, 3 June 2015

Helloworld Example Java

First of all we are going to see an example of hello world:



Java is an object oriented programming language.
First Line public class HelloWorld defines a class called HelloWorld.

public: its a access specifier and if its public then this class is accessible from any where. i.e. from any directory, any package, any application.

class: class is a keyword and which is used to declare a class. Java is an OOP language so each and every thing in java should be inside class.

HelloWorld: HelloWorld is a class name. You can give any name as class .

Note that if a class access specifier is public than it should always saved by className.java
here class name is HelloWorld and its access specifier is public so this Java file should be saved as HelloWorld.java.


public static void main(String[] args): main method is entry point for a Java class. It should be always static.

System.out.println( ): 

System: System is a class of java.lang package
out: out is a static member of System class and is an instance of java.io.PrintStream
println: println is a method of java.io.PrintStream. println method is overloaded to print the message in console.

Why main method is public static in Java

Syntax of java main method is:

public static void main(String[] args)
{

}

reason for public static void main are:

public: This is because public access specifier is accessible from any where. i.e. inside or outside of the application. And main method is entry point of a class so it should be accessible from anywhere.

static: As main method is an entry point of Java program, while invoking main method there wont be any object. That's why static is required for main method.
we all know while we want to invoke a method there should be an object or method should be static. As for static method no need of object, using class name we can invoke a static method.

void: Return type of main method is void, because Java is platform independent and if main method return any value then meaning of that value can be different in different system.

String[] args:   String[] args is an array of java.lang.String type.And this is specially used to store values received from console.

We all know that Java only deals with String, because we can store any types of value in string.
Thats the another reason for using String array as argument of main method.

Note that args is just a name you can give any name to this. ex: public static void main(String[] variable) and it will work
for ex: String s="123";
and easily we can convert 123 to no.