javaprogram-entry-pointentry-pointpublic-method

Is it possible to write Java code without public static void main(String[] args)?


I am studying for a very basic / beginners Java exam, and when reviewing some example code, I noticed a couple that did not include the method: public static void main(String[] args)

How is this possible? Is there something I am missing?

Example of example code my professor uploaded without the method:

public class Student {

  int midtermExam;
  int finalExam;
 
  double calcAvg() {
    double returnValue;
    returnValue = (midtermExam + finalExam) / 2.0;
    return returnValue;
  }

  char getLetterGrade() {

    char grade;
    double avg = (midtermExam + finalExam) / 2.0;
    // double avg = calcAvg();
    
    if (avg >= 90)
      grade = 'A';
    else
    if (avg >= 80)
      grade = 'B';
    else
    if (avg >= 70)
      grade = 'C';
    else
      grade = 'F';

    return grade;
  }

}

Solution

  • The public static void main(String[] args) method is the entry point for a standard Java application. You need at least one class with this method if you want to run it from the command line. There are some special cases where you can build a JAR without such entrypoint if that JAR is a library or a package that will somehow added to another application that will use it. But you don't want to go into that detail now.

    The examples you've seen are probably just that. Examples. And they lack the entrypoint because they are not complete applications. The code your professor uploaded is just a Class. It couldn't be executed. It is just a way of showing a class.