Structure of Java Program and Java Syntax Explained
Learn via video course
Overview
Java programming language is platform-independent and a secure programming language. Java has a pre-defined syntax and structure using which codes can be written. It is essential to understand basic Java syntax and structure of classes, objects and methods before we can write Java appliactions.
Scope
The article aims to:
- Explain the meaning of syntax and structure.
- Comprehend the code structure and syntax of Java.
- Explain foundational knowledge of Java code and syntax like Java modifiers, identifiers, keywords, etc.
- Help understand the structure of a Java program.
Introduction
As a programmer, you must have dealt with many programming languages. We must have observed that every programming language has some pre-defined code structure and a set of rules known as syntax. If these rules are violated while writing the code, it'll produce an error. It is very important to follow the syntax. Before understanding this in detail, let us know the history of Java.
Java was earlier called Oak. It was developed by James Gosling for the company Sun Microsystems in the year 1991. Java was later acquired by the Oracle Corporation. Oak was later renamed as Java which were the initials of many individuals who were involved in the project. They were James Gosling, Arthur Van Hoff andAndy Bechtolsheim. Thus, the language got its name.
Java is an Object-Oriented Programming language and a platform independent language means the Java compiled code which is the Byte Code can run on all operating systems. Programs are both compiled and interpreted in Java. Java programs are written within a class and it is a case sensitive language. It follows the principle of Write Once, Run Anywhere.
Java is a High Level Language. It means the user can understand and debug it easily. The code written in Java is compiled to Byte Code. This code is independent of the machine on which the program runs. When Byte Code is to be run on any system, JVM or Java Virtual Machine translates the byte code to machine code.
What is Java Syntax?
Syntax refers to a set of rules that define the structure of a programming language. It is a combination of words that are considered to be correctly structured for that language.
We will dive deeper into the world of Java and know more about syntax so that we can write a program based on it.
Class Section
This is a mandatory section. Each Java program has to be written inside a class as it is one of the main principles of Object-oriented programming that Java strictly follows, i.e., its Encapsulation for data security.
There can be multiple classes in a program. Some conventions need to be followed to name a class. They should begin with an uppercase letter.
main() Method
This is a compulsory part of the Java code. This is the entry point of the compiler where the execution actually starts. It is called/invoked by the Java Virtual Machine or JVM.
The main() method should be defined inside a class. We can call other functions and create objects inside this method. The following is the syntax that is used for defining.
Syntax
Example
Output Statements
Output statements in Java are used to display the result of any execution of the program written by the user. The values to be displayed on the screen are enclosed within the braces - (). There are two ways to write the output on the screen.
- System.out.print()- When this statement is used, the cursor remains on the same line after producing the result.
Example:
Output-
- System.out.println()- When this statement is used, the cursor shifts to the next line after producing the result. Here 'ln' acts as a line feed in order to make the cursor skip the existing line and move to the next line.
Example:
Output-
- System.out.printf() - The printf() method belongs to the PrintStream class which is used to format a string by a format specifier. A format specifier is preceded by a % symbol followed by the character which indicates the type of data (int, float, etc.) that will be converted to. It is equivalent to String.format() method.
- Parameters of System.out.printf() method:
- Locale- It specifies the locale format. It is a specific geographical, political or cultural location.
- Format- It is the format of the string.
- Args- It is the number of arguments for the format string. It can be 0 or more.
Syntax-
Example:
Output-
Explanation-
In the above example, we printed the number using the format specifier %f which is used for decimals i.e double data type. On the console, the output gets printed which is a double data type. The second one normally prints the number exactly as it is while the first one formats it to a double value and then prints.
Case Sensitive Language
Java is a case sensitive language. It means that the upper or lower case of letters in your programs matter and they are considered different. So, the variable names, classes, keywords have to be written verbatim in the program.
Example-
Hi and hi are considered two different words.
Now that we have known the basics of Java syntax, we can enter into the programming world by writing our first Java program.
Simple Java Program : Hello, Java!
Output-
Explanation-
In the above program we printed a line on the console using System.out.println() which gets displayed after the code gets executed.
Java Identifiers
Identifiers are used to name classes, methods and variables. It can be a sequence of uppercase and lowercase characters. It can also contain '_' (underscore) and '$' (dollar) sign. It should not start with a digit(0-9) and not contain any special characters.
Example-
Valid identifiers
AvgVal | new_var | temp9 | $count |
---|
Invalid identifiers
9obj | new-var | temp/id |
---|
Declaring Variables
Variables are also known as identifiers in Java. It is a named memory location which contain a value. We are allowed to declare more than one variable of the same type in a statement.
Syntax:
Example:
Explanation:
- In the first line,we are declaring a variable of type int and name var and initialising it with a value.
- The second line is just the declaration of an integer.
- The third line is declaring two characters in one statement.
Rules for Naming a Variable-
- A variable may contain characters, digits and underscores.
- The underscore can be used in between the characters.
- Variable names should be meaningful which depicts the program logic.
- Variable name should not start with a digit or a special character.
- A variable name should not be a keyword.
Java Modifiers
Access Modifiers or Access Specifiers are used to define the scope of classes, methods or constructors. There are 4 types of access modifiers in Java.
- Default- When no access modifier is specified, then it is said to have the default access modifier. It cannot be accessed from outside the package and is only accessible within that package.
- Public- The public access modifier is defined using the public keyword. This has the widest scope among access modifiers and this can be accessed anywhere within the program like within the class, outside the class, within the package and outside the package.
- Private- The private access modifier is defined using the private keyword. Methods or variables defined as private can be accessed within that class and not outside it.
- Protected- The protected access modifier is defined using the protected keyword. Methods or classes defined as protected can be accessed within that package and outside package by subclasses.
Access Modifier | Within Class | Within Package | Same Package by Subclasses | Outside Package by subclasses | Global |
---|---|---|---|---|---|
Public | Yes | Yes | Yes | Yes | Yes |
Protected | Yes | Yes | Yes | Yes | No |
Default | Yes | Yes | Yes | No | No |
Private | Yes | No | No | No | No |
Java Keywords
Keywords are also known as reserved words in Java. They carry some predefined meaning and are used throughout the program. They cannot be used as a variable name.
List of Keywords in Java
abstract | assert | boolean | break | byte | case | catch |
---|---|---|---|---|---|---|
char | class | const | continue | default | do | double |
else | enum | exports | extends | final | finally | float |
for | goto | if | implements | import | instanceof | int |
interface | long | module | native | new | open | opens |
package | private | protected | provides | public | requires | return |
short | static | strictfp | super | switch | synchronized | this |
throw | throws | to | transient | transitive | try | uses |
void | volatile | while | with |
Structure of Java Program
Apart from the above sections, there are some sections that play a crucial role in Java.
Comments
Comments are non-executable parts of a program. A comment is not executed by a compiler. It is used to improve the readability of the code.
Writing comments is a good practice as it improves the documentation of the code. There are 3 types of comments- single line, multi line and documentation comments.
- Single line comment- It is a comment that starts with // and is only used for a single line.
- Multi line comment- It is a comment that starts with /* and ends with */ and is used when more than one line has to be enclosed as comments.
- Documentation comment- It is a comment that starts with /** and ends with */
Import Statements
Import statements are used to import classes, interfaces or enums that are stored in packages or the entire package. A package contains many predefined classes and interfaces.
We need to mention which package we are using at the beginning of the program. We do it by using the import keyword. We either import the entire package or a specific class from that package.
The following is the description of how we can write the import statement.
Explanation-
We have imported java.util package in the first line and in the second line we have imported only the StringTokenizer class from java.util package.
Interface Section
This is an optional section. The keyword interface is used to create an interface. An interface contains a group of related methods with empty bodies i.e method declaration and constants.
Explanation-
In the above code we have defined an interface named Code which contains two method declarations namely write() and debug() with no method body. The body of abstract methods is implemented in those classes which implement the interface Code.
Methods
A method is a collection of statements that perform a specific task.The method names should start with a lowercase letter.
It provides the reusability of code as we write a method once and use it many times by invoking the method. The most important method is the main() method in Java.
In the method declaration, the following are the important components.
Modifier- Defines access type i.e., the scope of the method.
The return data type-It is the data type returned by the method or void if does not return any value.
Method Name- The method names should start with a lowercase letter (convention) and should not be a keyword.
Parameter list- It is the list of the input parameters preceded with their data type within enclosed parenthesis. If there are no parameters, you must put empty parentheses ().
Exception list- The exceptions that a method might throw are specified.
Method body- It is enclosed between braces {}. The code which needs to be executed is written inside them.
Method signature-It consists of the method name and a parameter list (number, type and order of the parameters). The return data type and exceptions are not a part of it.
Example:
Explanation-
In the above method, we have added two numbers that were passed as parameters and after adding, printed the result. This is only executed when the method is called.
Program File Name
So, you must be wondering about the process of naming your file in Java. In Java, we have to save the program file name with the same name as that of the name of public class in that file.
The above is a good practice as it tells JVM that which class to load and where to look for the entry point (main method).
The extension should be java. Java programs are run using the following two commands:
Conclusion
- Java is an Object Oriented Programming language which is case sensitive, platform independent, uses both compiler and interpreter.
- Java program consists of classes which are compulsory to be written.
- The main() method is the entry point of the compiler from where it starts the execution.
- Variables and identifiers are used for naming variables and classes.
- Keywords are reserved words which are predefined and have a meaning.
- Access modifiers are mainly used to define the scope of a class, method, constructor or data members.
- Java file should be saved with the name of the public class and should have the extension .java after the file name.