...

/

Java Program Structure

Java Program Structure

Begin your journey with a “Hello World” program in Java. Learn its syntax and structure while comparing Java and Python programming approaches.

This course is built upon the fundamental knowledge of Python programming. Starting with Python as a base, we will become acquainted with Java. The first step of our journey involves an introduction to the Java program, including its language structure and execution mechanism.


In this lesson, we’ll explore the structure of a Java program, starting with a simple “Hello World” example. We’ll dissect each component and compare it with its equivalent in Python.

Anatomy of a Java program: Hello World

In computer programming, one of the most fundamental tasks is to create a program called “Hello world!” This program is very simple and straightforward, which makes it a great starting point for newbies. Compared to more intricate programs, troubleshooting “Hello world!” is a breeze; the only difficult part is adhering to the rules in writing code. To simplify this concept, let’s examine the difference between the “Hello world!” program in Python and Java.



print("Hello world!")



public class HelloWorld {
    public static void main(String[] args) {
        
        System.out.println("Hello world!");
    }
}

Now, let’s see these in both languages:

Python

In Python, it’s as easy to print “Hello world!” as:

Press + to interact
print("Hello world!")

Java

Let’s see how we can print “Hello world!” in Java:

Press + to interact
public class MyJavaApp {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

Now, let’s take a look at a few more examples before diving deep into its components:

public class MyJavaApp {
// Main method - entry point of the program
public static void main(String[] args) {
// Use the Math.round() function to round the number to the nearest integer
// Store the rounded value in a long variable named 'roundedNumber'
double roundedNumber = Math.round(3.14159);
// Print the rounded number
System.out.println("Rounded number: " + roundedNumber);
}
}
Java number rounding example

See how the following slide takes apart almost the same code we just saw above and then snaps the pieces together like Lego blocks.

Press + to interact
canvasAnimation-image
1 / 5
  • Class name: Java is object-oriented, so code is organized into classes. The public class MyJavaApp line declares a class named MyJavaApp.

In Java, the file name must match the name of the public class defined within it. In this case, our file is named MyJavaApp.java. If the file name is not the same as the class name, it will throw a compilation error.

  • Main method: Every Java program starts executing from the main method. It is declared with public static void main(String[] args). Here:

    • public ...