×

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully comprehend the fundamental structure of a Java program before delving further.

The structure of the Java program contains the following sections:

  1. Documentation Section
  2. Package Declaration
  3. Import Statements
  4. Interface Section
  5. Class Definition
  6. Class Variables and Variables
  7. Main Method Class
  8. Methods and Behaviours

Documentation Section

For a Java programme, the documentation part is a crucial but optional section. It contains essential details about a Java programme. The name of the author, creation date, version, programme name, firm name, and description of the programme are all included in the data. It makes the software easier to read. Whatever we put in the documentation section is ignored by the Java compiler when the programme is running. We employ comments to format the statements in the documentation section. Single-line, multi-line, and documentation comments are all acceptable types of comments.

  • Single-line Comment: It starts with a forward slash (//).

    For example: //this is a java single line comment
  • Multi-line Comment: It starts with /* and ends with */.

    For example: /* this is a multi-line comment in java
  • Documentation Comment: It starts with (/**) and ends with */.

    For example: /**this is documentation section in java */

Package section

The declaration of the package is optional, and follows the documentation section immediately. We identify the package name where the class is located in this section. Keep in mind that a Java programme can only have one package statement. Before the definition of any classes or interfaces, it must be declared. It is required because Java classes can be put in several packages and directories depending on the module, they are used in. The package has a single-parent guide that it belongs to for all of these classes. To declare the package name, we utilize the word package. For instance:

package Tutorial; //tutorial is the declared package
package example. Tutorial; // Tutorial is the main package; an example is a subpackage.

Import Statements

The numerous predefined classes and interfaces are included in the package. Any class from a specific package must be imported before it can be used. The class stored in the other package is represented by the import statement. To import the class, we utilize the import keyword. It appears both after the package statement and before the class definition. The import statement can be used to import either a single class or all the classes in a given package. We can utilize numerous import statements in a Java program. For instance:

import java.util.* // it will import all the classes and methods from util package
import java.util.scanner // it will only import the scanner class
import java.lang.*
import java .awt.* 

Interface section

This part is optional. If necessary, we can build an interface in this part. To create an interface, we utilize the interface keyword. A class and an interface differ slightly from one another. It just has declarations for methods and constants. It cannot be instantiated, which is another distinction. The implements keyword lets us use interface in classes. By utilizing the extends keyword, an interface can also be utilized with other interfaces. For instance:

interface animal
{
  void shout ();
void hunt ();
void eat ();
void sleep ();
}

Class Definition

The class is defined in this section. It plays a crucial role in a Java software. We are unable to write any Java programs without the class. One or more class definitions may be contained in a Java program. We use the class keyword to define the class. The class serves as a Java program's template. It includes details on user-defined procedures, variables, and constants. The main () method is present in at least one class in every Java program. For instance:

class Tutorial // class declaration
{
            // methods declaration
// variable declaration
  // logic of the program 
// executable statements
}

Class variables and constants

We define variables and constants in this part that will be utilized later in the program. The variables and constants are defined immediately following the class definition in a Java application. The values of the parameters are stored in the variables and constants. It is employed when the software is being run. By utilizing modifiers, we can additionally determine and specify the range of variables. It establishes the variables' life. For instance:

class Tutorial // class declaration
{
            int size ; // variable declaration 
String name ;
double average;
 
}

main() Method

We define the main () method in this section. Every Java application requires it. Because all Java applications start out running in the main () function, in other words, it acts as the beginning of the class, obviously in the classroom. In the main method, we create objects and invoke the methods. We invoke the main () method without creating an object. The main () function can be called without the construction of an object since static methods can be invoked without creating objects. To define the main () method, we use the following syntax:

public class Tutorial 
{
public static void main (String a [])
{
// Variable declaration
// object creation
// method declaration
// method calls
}
} 

Methods and Behavior

Using the methods, we define the program's functionality in this part. The set of instructions we want to follow is included in the methods. Runtime execution of these instructions completes the requested task. A method is a part, group, or body of code that is used to carry out a certain operation or action. Code can become more reused thanks to it. Once developed, a technique is applied repeatedly. You are not needed to write the same code repeatedly. Additionally, simply adding or removing a block of code, it provides straightforward code modification and readability. The method is executed when it is called or invoked. For instance:

public class Tutorial 
{
public static void main (String a [])
{
void display ()
{
system.out.print(“Welcome to tutorial and example”);
}
// statements
}
} 

Let’s try to write a program by following all the above documentation steps:

StringCount.java

/* java program Documentation
A string is provided to you; your task is to determine the frequency of each character in the string and output that information. You can solve this problem by utilizing a hashing algorithm or a hash map. When generating a hash map, you must give a character as the key record and an integer as the value record. The characters of the given string must now be stored in the key record, according to logic. You must keep track of how many characters are in the string in each key-value record. If a character appears again, the hash map's frequency count for that character needs to be increased. Finally, you need to traverse the hash map and print the character along with its count values */
// import the required packages


import java.io.*;
import java.util.*;
import java.lang.*;
public class StringCount
// class declaration
{
public static void main (String [] args) 
  // main method declaration
{
Scanner sc = new Scanner (System.in);
// scanner class for input at runtime
                      System.out.println(“Please enter the String:”);
String repString = sc.next ();
// string input
FrequencyString StringFreq=new FrequencyString();
// object creation and calling
     StringFreq.Frequency (repString);
}
}
class FrequencyString
{
    void Frequency (String s)
// not static method of FrequencyString class out of main class
    {
        HashMap<Character,Integer> Freq = new HashMap <> ();
        // Hash map creation for storing characters and integers for easy traversal
        for (int i = 0; i < s.length (); i++)
        {
            if (Freq.containsKey (s.charAt(i)))
            {
                Freq.put (s.charAt (i), Freq.get (s.charAt (i))+1);
// increasing count if the character is already present in the string
            }
            else
            {
                Freq.put (s.charAt (i),1);
     // Storing each character of string in hashmap if it is not present in the  
       // hashmap
                
            }
        }
        
        for (int i = 0; i < s.length (); i++)
        {
            if (Freq.get (s.charAt (i)) != 0)
            {
                System.out.println(s.charAt (i)+" -> "+Freq.get (s.charAt (i)));
       // printing the character frequency in the string along with the 
                // character
                Freq.put (s.charAt (i),0);
            }
        }
    }
}

Output:

Structure of Java Program

Related Topics

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively...

4 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Java Characters

Normally, when we work with characters, we use primitive data types char. When we have to work with the objects of char, we use Character class. Character class has many important...

2 minutes read.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Java Networking

Networking Networking is a way of communicating the devices. It is made up of various technologies like computers, switches, routers that are interconnected and share data among themselves. The two common network protocols: 1. TCP/IP TCP stands for...

10 minutes read.

Ordinal Number in Java

What is the Ordinal Number in Java? An object's or person's position or rank can be expressed mathematically using an ordinal number. Depending on the criteria used to establish the positions,...

3 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.