The main() method, A First Java Program, Compiling and Executing

The main() method
  • In Java, every application begins with a class name, and that class must match with filename.
  • Filename: MyClass.java
Class:
public class MyClass {

}
  • Every line of code that runs in Java must be inside a class. 
  • For Example class MyClass
  • A class should always start with an uppercase first letter.
  • The main() method is mandatory.
  • You will see the main() method in every Java program.
  • For example:
public static void main(String[] args)
{
}



  • Any code inside the main() method will be executed. 
  • Inside the main() method, we can use the println() method to print a line of text to the screen.
  • Example: System.out.println("Hello World");

    • Note: Every program must contain the main() method.
      Note: The curly braces {} marks the beginning and the end of a block of code.
      Note: Each code statement must end with a semicolon (;).
    There are total three phases:
    (1) Writing Program Phase
    • Let's create java program which display string
      • Step 01: Open Notepad or any Editor such as notepad++, Netbeans.
      • Step 02: Write the following code.
    public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello World");
      }
    }
      • Step 03: Save the program as MyClass.java.


    Note: Java program has .java extension to save program.

    (2) Compiling Phase
    • Step 01: Open Command Prompt (cmd.exe)
    • Step 02: Navigate to the directory where you saved your file.
    • Step 03: Type "javac MyClass.java" & generate bytecode with ".class" file.

    Note: Javac compiler will compile your code. If there are no errors in the code, the command prompt will take you to the next line.

    (3) Executing Phase
    Step 01: Type "java MyClass" and it will display output as "Hello World".

    Thanks a lot for query or your valuable suggestions related to the topic.

    Previous Post Next Post

    Contact Form