Skip to content

Anatomy of a Java Program

Let’s go through the anatomy of a Java program

A function is the smallest building block used to perform tasks in a Java program. Every Java program requires at least one function, which serves as the entry point to the application. This entry point is always the main function.

Example function code block:

ReturnType Name(parameters) {
...
}
  • The ReturnType specifies the type of value the function will return. If no value is expected, the return type is void.
  • A function cannot exist independently and must be defined within a class.

A class is a container that can hold one or more related functions (or methods). Every Java program requires at least one class that contains the main entry point to the program. The name of this class is commonly Main, but this can vary.

Example of a class with the main function:

class Main {
void main() {
...
}
}

In Java, the functions defined within a class are called methods.

Access modifiers are special keywords used to define the visibility or accessibility of classes and their members (methods, variables, etc.). Common access modifiers include:

  • public: Accessible by any other class.
  • private: Accessible only within the same class.

Example with an access modifier:

public class Main {
public static void main(String[] args) {
...
}
}
  • In Java, class names follow the PascalCase convention, where the first letter of each word is capitalised (e.g., Main, CustomerService).
  • Method names follow the camelCase convention, where the first letter is lowercase, and the first letter of subsequent words is capitalised (e.g., calculateInterest(), printReceipt()).

Packages are used to properly group and organise classes.

Primary Source Daniel Ross - JavaCJava Series

  1. Do not name your package Java or JavaX
  2. Use lower case
  3. Name your package the reverse of your internet domain name

A good example would be: suffix.domain.namespace that can translate to something like dev.asbedb.hello

Recommended folder structure

src/<domain_suffix>/<domain_name>/<package_namespace>/PackageName.java

There are two primary steps involved here Compilation and Execution

In the compilation step VS Code is using the Java compiler to compile our source into Java bytecode. You can invoke the compiler by using the javac command to see your compiled bytecode in a .class file. When you are using the IDE to run and debug your .java files the compiled output is held in a mirrored directory structure starting with bin rather then src(other IDE’s may have different naming conventions).

Compiled java .class files are enabled to be platform independent and can run on any operating system that supports the Java runtime environment.

The Java runtime environment has a component called the Java Virtual Machine (JVM) which takes the Java bytecode from the .class file and converts it to native executable code of that operating system.