VisualStudioTutor.com Java Tutorial All Lessons

Lesson 5 of 20

Your First Java Program

Understand the structure of a Java class, the main method, statements, comments, and console output.

Learning objectives

  • Identify the class declaration and main method.
  • Explain what public, static, and void mean at a beginner level.
  • Write output with print, println, and printf.
  • Use single-line and multi-line comments.
  • Compile and run a complete Java program.

1. The basic program structure

Every example in this lesson is contained inside a class. For a simple console application, execution starts in the main method.

Example: HelloStudent.java

public class HelloStudent {
    public static void main(String[] args) {
        System.out.println("Welcome to Java programming!");
    }
}

public class HelloStudent defines a class. public static void main(String[] args) is the entry point. The braces { } group the statements that belong to the class and method.

2. Printing text

println prints a value and then moves to a new line. print leaves the cursor on the same line. printf supports formatted output.

Example: three output methods

public class OutputDemo {
    public static void main(String[] args) {
        System.out.print("Java ");
        System.out.println("is running.");
        System.out.printf("I am learning lesson %d.%n", 5);
    }
}

Expected output

Java is running.
I am learning lesson 5.

3. Comments

Comments document intent and are ignored by the compiler.

public class CommentDemo {
    public static void main(String[] args) {
        // This is a single-line comment.
        System.out.println("Comments help explain code.");

        /*
           This is a multi-line comment.
           It can span several lines.
        */
    }
}

Mini project: personal profile card

Create a console program that displays a simple profile using both println and printf.

public class ProfileCard {
    public static void main(String[] args) {
        String name = "Daniel";
        int age = 20;
        String course = "Computer Science";

        System.out.println("=== Student Profile ===");
        System.out.println("Name   : " + name);
        System.out.printf("Age    : %d%n", age);
        System.out.println("Course : " + course);
    }
}

Common mistakes

ProblemWhy it happensHow to fix it
Missing semicolonA statement is not terminated.Add ; at the end of the statement.
Using smart quotation marksText copied from a word processor may use curly quotes.Use normal Java quotes: "text".
Wrong main method signatureJava cannot find the entry point.Use public static void main(String[] args).

Summary

You can now read and write the basic structure of a Java console program. The next lesson introduces variables and data types so programs can store information instead of only printing fixed text.