Welcome back to the Java tutorial series. In the previous tutorial we ran our first hello world Java program in Eclipse IDE. In this tutorial, we shall try to understand the general syntax of Java Program.
Let us revisit the program which we wrote in the previous tutorial.
package com.comp.name1;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(“Hello”);
}
}
Every Java program starts with a package name. It is basically the folder structure under which your program file exists.
For e.g. the Package name in the above example is:
Every Java program contains a class. The file name of this Java program should be same as the class name. As per standard programming practice, the first letter of the file name and class name should be in uppercase.
For e.g. the Class name in the earlier example is shown below:
Here, you can notice that the keyword “public”. It is an access modifier in Java which we will explore in depth later. You can also keep this as line as “class HelloWorld{}”, it should work fine as well.
Once the class is created, we need to create a main method with the below standard syntax:
Do not change the name of this statement. When a Java file is executed, it searches for this method first to start the program execution. You can include additional methods (or function if you come from C programming background) inside the same Java file, however the execution starts from the above Main method.
Once the main method is created, we need to write our code statements inside this Main method.
For e.g. one such code example is given below:
This code statement prints or logs the word “hello” in the console output.
Every code statement should be written inside the curly braces {} of the respective method. The curly braces marks the scope of execution for the respective method. It is also referred to as code blocks.
Every code statement or line should be followed by a semi colon. If you fail to include a semi colon, you will get an “Unresolved compilation problem” syntax error as shown below:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error, insert ";" to complete BlockStatements
If you do not want to run any line of code during program execution, you can comment out that code. Comments are also useful when you want to add some notes or documentation or TODO action for better readability of fellow programmers.
// System.out.println(“This line will not run”);
/*
This is a multi line comment.
System.out.println(“This line will not run”);
*/
I hope you got an understanding of basic Java syntax. See in you soon in the next tutorial.
Next Chapter Java Variables
Fully customizable CRM Software for Freelancers and Small Businesses