In this post I will explain the structure of a Java program. A Java program is a collection of one or more classes, in which, one class contains the main method. Before looking at the structure of a Java program, let’s see the structure of a Java class.
Structure of a Java class is as shown below:
A Java class can contain the following:
- Package statement: A package statement is used to declare a Java class as a part of the specified package. More on declaring packages later. Package statement is optional. When we decide to write a package statement, it should be the first statement in the file. Only exception to this rule is writing comments.
- Import statement(s): We can write one or more import statements. These are also optional. An import statement is used to link our class with other classes in the same package or other packages to use their functionality. More on import statement in other articles.
- Comments: We can write one or more comments in a Java class to explain the use of certain statements or provide extra information like purpose of the class, author’s name, date and time of creation etc. Comments are optional. Comments can be written in the first line or anywhere in the program. More on writing comments later.
- Class declaration: A class declaration consists of the class keyword followed by the class name, which is followed by the body of the class represented using braces { }. A class declaration can contain the following:
- Variable declarations
- Comments
- Constructors
- Methods
- Nested classes
- Nested interfaces
- Enumerations
All the above elements (variable declarations, comments etc…) can occur in any order.
Now, let’s look at the structure of a Java program. It will be as shown below:
As I had already mentioned above, a Java program is a set of one or more classes in which each class will be declared following the structure of a Java class and one of the classes will have a main method to start the execution of the Java program.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply