In this post, we will learn how to write first Java HelloWorld program. To create java program, you need to create a class that contain main method.
The process of java program involve three simple step
- Write java program in text editor and save it to a file called HelloWorld.java
- Compile the code on terminal by typing "javac HelloWorld.java"
- Run the java program on terminal by typing "java HelloWorld"
Below is the simple Hello World program of java that will print "Hello World!" on terminal.
class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }
In Java, We must learn about the name of source file that is very important. In this case, name of the source file is HelloWorld.java.
In Java, a source file is officially called compilation unit. It is a text file that contains one and more class definitions. The Java compiler need a source file with .java filename extension.
In Java, all code must reside inside a class.
By convention, The name of main class should match with the name of file that hold the program.
Let's understand each and every piece of above Hello World java program
- class HelloWorld { This line used the keyboard class to declare that a new class is being defined. HelloWorld is an identifier that is the name of the class. The entire class definition, including all of its members, will be between the opening curly brace { and the closing curly brace }.
- public static void main(String[] args) { Every Java application begin execution by calling main() method.
- The next line of code is shown here. Notice that it occurs inside main( ).
System.out.println("Hello World!");
This line outputs the string "Hello World!" followed by a new line on the
screen. Output is actually accomplished by the built-in println( ) method. System is a predefined class
that provides access to the system,
and out is the output stream that is connected to the console.
Notice that the println( ) statement ends with a semicolon. All statements in Java end
with a semicolon.
The first } in the program ends main( ), and the last } ends the HelloWorld class definition.
Compiling java program
Once you have installed JDK in your machine. You can open open terminal in your machine and go to the the source code directory where file - HelloWorld.java is present.
Now, compile the HelloWorld program by executing the command javac, specifying the name of the source file on the command line, as shown:
The compiler creates a file called HelloWorld.class (in present working directory) that contains the bytecode of the program.
Now, execute the program, JVM(Java Virtual Machine) needs to be called using java, specifying the name of the class file on the command line, as shown:
This will print "Hello World!" to the terminal screen.
No comments :
Post a Comment