Simple Java Program Example with Explanation
Now that you have gained the basic knowledge about Object Oriented Programming Concepts, Lets write a simple Java Program and try to dissect it.
This is a sample Java Program
to help you kick-start with Java
public class MyFirstClass
// The main() method is the starting point of execution of a Java Program
public static void main(String args)
System.out.println("Hurray!! My First Java Program actually Executes !!!");
Dissection of a Java Program
1. Multi Line Comment
The first few lines starting with "/*" and ending with "*/" are multi-line comments. Multi line comments are useful while describing about a method or a class to help other developers understand the code.
2. public class MyFirstClass
The line "public class MyFirstClass" states that a new class is being created.
The statement " class MyFirstClass " will also work as the default access specifier in Java is "Default".
3. public static void main (String args)
The meaning of "public static void main (String args)" is explained through the following figure.
- Public Access specifier allows the method to be accessed from outside the class.
- Static means that to call the main method an instance variable of the class is not required. It can be accessed directly using ClassName.functionName()
- void means that the method main does not return anything.
- The arguments String args means that main accepts as arrays of Strings . In this case since main is called by the OS, the arguments of main() method is a list of command line arguments.
4. Single Line Comment in Java
Single line comments start with // and are used often to provide short description of statement in a Java program.
The statement "System.out.println" prints the parameter passed to it on the console by default.
It can also evaluate an expression passed to it as an argument and then print the result of the expression.
There are two variations of it:
- print() : It prints in a single line and does not append a newline character at the end.
- println() : It appends a newline character at the end.