Understanding what is public static void main in Java class


When looking class in Java, sometimes you see “public static void main” of some class name. So, let we learn about what it means in Java. First, we create a new Class in Java on files called “car.java” :

1
2
3
4
5
6
7
8
9
10
11
12
class Car {
    /** Default gear */
    int gear = 1;

    void updateGear(int newValue) {
        gear = 2;
    }

    void printStates() {
        System.out.println("Gear position : " + gear);
    }
}


This Car class have methods called “updateGear”. This method using void which it means doesn’t throw any value (to it’s caller). Void is kind of type for the result that function return normaly.

Now, let try execute this class. To execute in Ubuntu, you can do by :

1
2
javac car.java
java Car

And it will throw results :

1
Exception in thread "main" java.lang.NoSuchMethodError: main

Yes, this is when java execute compiled files, it will try to execute class that have main.
Then let create implementation of this Car class :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Car {
    /** Default gear */
    int gear = 1;

    void updateGear(int newValue) {
        gear = newValue;
    }

    void printStates() {
        System.out.println("Gear position : " + gear);
    }
}

class CarDemo {

    public static void main(String[] args) {
        Car car1 = new Car();
        Car car2 = new Car();

        /** Car 1 go to gear 2 */
        car1.updateGear(2);
        car1.printStates();

        /** Car 2 still on default gear */
        car2.printStates();
    }
}

To execute in Ubuntu, you can do by :

1
2
javac car.java
java CarDemo

This will return :

1
2
Gear position : 2
Gear position : 1

Java can execute this CarDemo because it have main.

Futhermore explanation about public static and void :

A. public for this Class
It’s mean it can be accessed from any objects who imported this class.

B. static for this Class
It’s mean it is Class method.

C. void for this Class
It’s mean this class not return any value.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.