Code Structure

... by Bittle in Java Tutorial January 11, 2019

The main components

Java has 3 main components: source files, components, and methods!


What goes in a Source File?

A source code file has the .java extension and holds one class definition.


What Goes in a Class?

A class can have one or several methods.


What Goes in a Method?

You write instructions within methods. Method statements are procedures or sets of statements.


Main Method

In java, everything goes in a class. When you run the Dog class (shown below) you are telling the Java Virtual Machine to load the class and start executing its main method. We will go into more detail in the next section, but for now, all you need to know is that it all begins in main. No matter how many lines of code, you must have a main method.


Example Class

public class Dog {
    public void bark(int times) {
        // for loop. Loop from 0 to times-1
        for (int x = 0; x < times; x++) {
            System.out.println("bark!");
        }
    }

    // main method! Everything starts here
    public static void main(String[] args) {
        Dog choco = new Dog();
        choco.bark(3);
    }
}


output:

bark!
bark!
bark!

Comments (0)

Search Here