Basic Syntax

Declaring Classes

🙋 Need help? Ask an expert now!

Everything that a program accomplishes is outlined between the first brace and the final brace of the class. The line public static void main (String[] args) show where the program starts running. Please take a look at the code below that shows a class with a main method.

ClassExample.java
package exlcode;
 
 public class ClassExample { 
  // This creates new String named exampleVariable 
  private static String exampleVariable; 

  // This is the constructor for the class 
  // that takes in one parameter 
  public ClassExample(String exampleVariable){ 
    this.exampleVariable = exampleVariable; 
  } 

  public static void main(String[] args) { 
    // This will be explained in Unit 8 
    ClassExample classexample = new ClassExample("Hello World!"); 
    // This prints the String stored in exampleVariable 
    System.out.println(exampleVariable); 
  }
}

The class ClassExample is an example of a class declaration. The area between the braces is called the class body and provides all the code information within a certain class.

Please remember that if you are planning to run the class, the main method must exist and be declared exactly the same as it is show above. The class is separated into three different sections:

  1. Fields: contains variables that are declared or declared and initialized with a value
  2. Constructors: initialize the objects of a particular class. We will dive deeper into this concept when we examine and discuss objects
  3. Methods: sets of code that are referred to by name and called upon at any point in the program.
Edit Me on GitHub!

Application Question

Which of the following is the proper way to declare the main method?