- This example is just displaying a string named "Hello World".
example:-
import java.lang.*; // Java defaultly import this package.
class hello //class name should be same as the file name you saved{
public static void main(String args[]){
System.out.println("Hello World");
}
}
Output:-
- Let us elaborate this example, have a look at the very first line of program "import java.lang.*;". Java automatically import this package when ever you type your program. This package provides classes that are fundamental to the design of Java programming language, in this package the most important classes are object, which is the root of class hierarchy and class, instances of which represent classes at run time.
- The second line of our program "class hello" which should be similar to the program file you created, because the JVM(Java Virtual Machine) compile your program based on the name of your class so it can give a similar byte code file".class".
for example:-
Output:-
In this example the compiler will generate the byte code but it won't be able to executed it and will give an error saying "Could find or load main class 'file name' " because the name of the file and class names are different.
- The third and the most important line to understand is "public static void main(String args[])".
Purpose of writing public to main()
The main() is invoked by JVM that stays outside the package of the class to which main() belongs. If main() is not declared as public then it won't be accessible outside the package and JVM cannot invoke it. Hence we wan't main() to be accessible outside package so it is declared as public.
Purpose of writing static to main()
If main() is not declared as static, then JVM will need to create object main(). But since, main() is all entry point of Java program no objects are allowed to be created before main() is invoked. So we don not wan't main() to be invoked using object, hence it is declared as static. As to call static function object is not created.
Purpose of writing String args[]
The "args[]" is an array whose type data type is String, in this array we can store various string arguments by invoking them at the command line for example:- myProgram Shaan Royal, then Shaan and Royal will be stored in the array as args[0] = "Shaan" and args[1] = "Royal". You can do this manually also inside the program, when don't call them at command line.
- The last line "System.out.println();" is an output statement, in which System is a class in the java.lang package. ".out" is a static member of System class, and is an instance of java.io.PrintStream, "println" is a method of java.io.PrintStream. This method is overloaded tom print message to output destination, which is typically a console or file.