Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Documentation Section
3.
Package Declaration
4.
Import Statements
5.
Class Declaration
6.
Interface Section
7.
Class Variables & Constants
8.
Main Method Class
9.
Methods and Behavior
10.
Frequently Asked Questions
10.1.
Can I have more than one main method in a Java program?
10.2.
Why do we use public static void main(String[] args) in Java?
10.3.
Is it necessary to declare a class public?
11.
Conclusion
Last Updated: Apr 4, 2024
Medium

Structure of Java Program

Author Rinki Deka
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Java stands out as one of the most popular programming languages, widely used for building simple & scalable applications. It's not just about writing code; it's about organizing it in a way that makes sense, is easy to read, & maintain. 

Structure of Java Program

This article will talk about the key components that make up a typical Java program. From documentation to methods, you'll get a clear picture of how a java program works.

Documentation Section

Every Java program can start with a section called the Documentation Section. Think of this part like the cover page of a book or the summary on the back. It doesn't have codes that the computer reads. Instead, it's for anyone who looks at the code. This section can have comments that explain what the program is about, who wrote it, and what it's supposed to do. In Java, we write comments in two main ways: using // for short, one-line comments, or /* and */ for longer comments that might take up several lines.

Here's a simple example:

// Program Name: Hello World
// Author: Jane Doe
// Date: March 28, 2024
// Description: This program prints "Hello, World!" to the screen.


This doesn't change how the program works, but it helps others understand what's going on, making the code easier to work with, especially in big projects or when you're part of a team.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Package Declaration

In Java, the very first line of code in many programs is the package declaration. It's like telling your program where to find its books in a huge library. Each 'book' or 'package' is a collection of related classes (codes) that work together.

Here's how you might see it in a program:

package com.example.myfirstprogram;


This line tells Java that your program belongs to a larger group called com.example.myfirstprogram. It's a way to organize your code so that it's easier to find and manage, especially when your projects get really big. You don't always have to use a package declaration, especially for simpler programs, but it's good practice for when your code starts to grow.

Import Statements

After the package declaration, a Java program often includes import statements. These statements tell your program about the extra tools it needs from Java's toolset, which is vast. Just like when you're doing a project and you gather all the materials you need before you start, import statements gather all the tools your program will use.

For example, if you want to work with lists of items, you might use:

import java.util.ArrayList;


This line brings in the ArrayList tool from Java's utility package, so you can create lists in your program. It's like picking a specific tool from a toolbox; you're telling your program, "Hey, I'm going to need this."

Remember, Java has a huge collection of these tools, so you only bring in what you need. This keeps your program neat and efficient.

Class Declaration

In Java, the real action starts with the class declaration. This is where you define a blueprint for what your program will do. You can think of a class like a recipe: it tells Java how to make an object that can do certain things and hold certain information.

Here’s a basic example:

public class MyFirstJavaProgram {
    // Code for the class goes here
}


In this piece of code, public class MyFirstJavaProgram is like saying, "I'm creating a new recipe named MyFirstJavaProgram." Everything that goes inside the curly braces { } is part of the recipe. This is where you'll add your instructions (or code) that make your program work.

Classes are essential in Java. They help you organize and structure your code, making it easier to read and manage, especially as your programs get more complex.

Interface Section

In Java, an interface is a bit like a contract or a set of rules that certain parts of your code agree to follow. It's a way of ensuring that different parts of your program can work together smoothly, even if they're written in different ways. An interface defines a set of methods but doesn't provide the actual implementation of these methods. It's up to the classes that "sign" this contract to provide the specific details of how these methods work.

Here's a simple example of an interface:

interface Drawable {
    void draw();
}


In this example, Drawable is an interface with a method draw(). There's no code inside draw() here, just the declaration. Any class that implements this interface must provide the specific code for draw().

For instance, if you have a class for a Circle and a Rectangle, and both can be drawn, they might look like this:

class Circle implements Drawable {
    public void draw() {
        // Code to draw a circle
    }
}
class Rectangle implements Drawable {
    public void draw() {
        // Code to draw a rectangle
    }
}


Both Circle and Rectangle agree to the Drawable contract by implementing the draw method. This way, even though they are different shapes, you know they can both be drawn because they follow the Drawable interface rules.

Interfaces help make your code more flexible and modular, making it easier to grow and change over time.

Class Variables & Constants

In Java programs, class variables and constants hold the data your application needs to work with. Class variables are shared across all instances of a class, making them a common storage space accessible to every object created from that class. Constants, on the other hand, are variables whose values cannot change once set. They are the unchanging pillars of your code, ensuring that some values remain consistent throughout the execution of your program.

Here's how you might define class variables and constants in Java:

public class School {
    // Class variable
    static int numberOfStudents;
    // Constant
    static final String SCHOOL_NAME = "Greenwood High";
}


In this example, numberOfStudents is a class variable. It can be used to keep track of the number of students enrolled, and since it's static, this number is shared among all instances of the School class. On the other hand, SCHOOL_NAME is a constant, denoted by the use of final. Its value, "Greenwood High", cannot be changed once it's set.

Class variables are useful for when you want to have a piece of data that's shared across all objects created from a class, like a counter or a shared configuration. Constants are essential for values that should never change once your program starts, like configuration settings, error codes, or fixed values like the number of days in a week.

Main Method Class

The main method in Java is where the magic starts; it's the entry point of any Java program. Think of it as the ignition key for a car. Without turning the key, the car won't start. Similarly, without the main method, your Java program won't run.

Here’s how it looks:

public class MyFirstJavaProgram {
    public static void main(String[] args) {
        // Your code goes here
    }
}


In this setup, public static void main(String[] args) is a special line. Here's what it means:

  • public means anyone can access it.
     
  • static means you don't need to create an object of the class to use this method.
     
  • void means this method doesn't return any value.
     
  • main is the name of this method, which Java looks for to start the program.
     
  • String[] args can hold any command-line arguments that you might want to pass to your program.
     
  • Inside the curly braces { } after main, you'll put the instructions that you want to run when your program starts.

Methods and Behavior

In Java, methods are like actions or tasks. Each method in a class can do something specific. Think of methods as the verbs in your program; they make things happen with the data (the nouns). The behavior part is how these methods operate and interact with the data within your class or with other classes.

Here's a simple example to illustrate a method in Java:

public class Calculator {
    // Method to add two numbers
    public int add(int number1, int number2) {
        return number1 + number2;
    }
}


In this Calculator class, there's a method called add that takes two numbers as inputs (parameters) and returns their sum. The line public int add(int number1, int number2) is how you define the method. It tells Java that this method is accessible to other classes (public), it will give back an integer (int after public), and it's called add. The part inside the curly braces { return number1 + number2; } is the actual task or action the method performs.

Methods help you organize your code by breaking down tasks into smaller, manageable pieces. This way, you can reuse code easily without repeating yourself and make changes in one place without affecting other parts of your program.

Frequently Asked Questions

Can I have more than one main method in a Java program?

In Java, you can have multiple main methods, but only one of them can serve as the entry point in a given application, defined within a specific class.

Why do we use public static void main(String[] args) in Java?

This specific signature is used because it's the entry point recognized by the Java runtime. public makes it accessible from anywhere, static allows it to run without creating an instance of the class, void means it doesn't return any value, and String[] args can receive command-line arguments.

Is it necessary to declare a class public?

Not always. If a class is not declared public, it's accessible within its own package but not from outside. Declaring a class public makes it accessible from any other class.

Conclusion

In this article, we learned the fundamental structure of a Java program, starting from the very basics like documentation and package declaration, moving through import statements, class and interface declarations, and looking into class variables, constants, and methods. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Java Program to Compute GCD
Next article
Difference Between Java and Core Java
Live masterclass