DEV Community

Cover image for Exploring Classes and the Main Method in Java
Ricardo Caselati
Ricardo Caselati

Posted on

Exploring Classes and the Main Method in Java

If you're new to Java, it's important to know that classes and the special method public static void main are key to creating any program. Let’s dive into how they work in a practical and straightforward way!

What Are Classes in Java?

Classes are the building blocks of Java programs. They act as blueprints containing methods (or functions) that perform specific tasks. Imagine you're building a house: the blueprint represents the class, and the functional rooms are the methods that bring the house to life.

For example, a library system class might include methods for borrowing and returning books. However, to use these methods, you first need to create an object based on the class—just like you need to build the house before living in it.

Creating a class is simple. Use the class keyword, like this:

public class HelloWorld {

}
Enter fullscreen mode Exit fullscreen mode

Keep in mind that in most cases, the class name should match the filename, as shown in the example above.

The Starting Point: public static void main

Every Java program begins with the main method, which acts as the program’s entry point. This special method is required (except in libraries) and must be included within a class. Here's how it looks in the HelloWorld class:

public class HelloWorld {

  public static void main(String[] args) {
    // The program starts executing here
  }

}
Enter fullscreen mode Exit fullscreen mode

You can have multiple classes, each with its own main method. This allows the program to start from different points, depending on your IDE settings.

Displaying Messages in the Console

To output messages in the console, you can use the System.out.println() or System.out.print() commands. What’s the difference? println adds a new line after the message, while print keeps the cursor on the same line.

Here’s an example using println:

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("First Line");
    System.out.println("Second Line");
  }
}
Enter fullscreen mode Exit fullscreen mode

And an example using print:

public class HelloWorld {

  public static void main(String[] args) {
    System.out.print("First Line");
    System.out.print("This will also appear on the first line");
  }
}
Enter fullscreen mode Exit fullscreen mode

These tools are essential for beginners, helping you test and understand how your code behaves. So, roll up your sleeves, create a project in IntelliJ, try these examples, and watch the magic happen! 🚀

Top comments (0)