Skip to content

Module 1 · Getting Started with Java — topic 3 of 3

Your First Java Program

The anatomy of a Java program line by line: classes, the main method, statements, comments, printing and reading command-line arguments.

Beginner 12 min read·Lesson 3 of 39 in Java Programming

Learning objectives

  • Explain every word in the main method signature
  • Use println, print and printf
  • Write single-line, multi-line and documentation comments

Definition

A Java program is one or more classes; execution begins at the method public static void main(String[] args) of the class you launch, and proceeds statement by statement.

Introduction

Every Java program you write in this course starts from the same template. It looks like a lot of ceremony for printing one line, but each word has a precise meaning, and once you understand them the rest of the language follows naturally.

Why it matters

Misreading the template causes the most common beginner errors: main not found, wrong file names and missing semicolons.

Printing with printf is how every project in this course formats tables and reports.

Detailed explanation

public class Main declares a class named Main that any other code may use. Class names start with a capital letter.

public static void main(String[] args): public so the launcher can call it; static so it can run without creating an object first; void because it returns nothing; main is the required name; String[] args receives any command-line arguments as an array of strings.

Inside the braces are statements, each ending with a semicolon. They run from top to bottom unless control-flow statements change the order.

System.out is the standard output stream. println prints and then moves to a new line, print prints without a newline, and printf (or String.format) formats values using placeholders such as %d for integers, %.2f for decimals, %s for strings and %n for a platform-correct newline.

Comments are ignored by the compiler: // until the end of the line, /* ... */ across lines, and /** ... */ documentation comments that the javadoc tool turns into HTML documentation.

Java is case-sensitive: System, system and SYSTEM are three different names, and only the first one exists.

Syntax

Java
/** Documentation comment describing the class. */
public class Main {
public static void main(String[] args) {
// a single-line comment
System.out.println("text"); // prints a line
System.out.print("no newline ");
System.out.printf("%s is %d%n", "x", 5); // formatted output
}
}
  • %d int/long, %f or %.2f floating point, %s any value, %c char, %b boolean, %n newline.
  • %5d pads to width 5 (right aligned); %-10s pads to 10 (left aligned).
  • Strings use double quotes; single characters use single quotes.

Code examples

print, println and printf

Java
public class Main {
public static void main(String[] args) {
System.out.print("Hello, ");
System.out.println("world!");
System.out.println("Sum: " + (2 + 3));
System.out.printf("%s scored %d marks (%.1f%%)%n", "Asha", 455, 91.0);
}
}
Output
Hello, world!
Sum: 5
Asha scored 455 marks (91.0%)

%% prints a literal percent sign.

String concatenation surprises

Java
public class Concat {
public static void main(String[] args) {
System.out.println("1 + 2 = " + 1 + 2);
System.out.println("1 + 2 = " + (1 + 2));
System.out.println(1 + 2 + " is the sum");
}
}
Output
1 + 2 = 12
1 + 2 = 3
3 is the sum

+ works left to right: once a String is involved, the rest is concatenated.

More examples

A formatted receipt

Java
public class Receipt {
public static void main(String[] args) {
String[] items = {"Notebook", "Pen", "Calculator"};
int[] qty = {3, 10, 1};
double[] price = {45.50, 10.00, 799.00};
double total = 0;
System.out.printf("%-12s %4s %10s%n", "Item", "Qty", "Amount");
for (int i = 0; i < items.length; i++) {
double amount = qty[i] * price[i];
total += amount;
System.out.printf("%-12s %4d %10.2f%n", items[i], qty[i], amount);
}
System.out.printf("%-12s %4s %10.2f%n", "Total", "", total);
}
}
Output
Item          Qty     Amount
Notebook        3     136.50
Pen            10     100.00
Calculator      1     799.00
Total                1035.50

Step-by-step explanation

  • Three parallel arrays hold the item names, quantities and prices.
  • %-12s prints a string left-aligned in 12 characters; %4s and %10s right-align the headings.
  • The for loop visits each index from 0 to items.length - 1.
  • %4d prints the quantity right-aligned in 4 columns and %10.2f prints the amount with two decimals in 10 columns.
  • The final line passes an empty string for the quantity column so the total lines up under the amounts.

Expected output

Running “A formatted receipt” prints exactly:

TextOutput
Item Qty Amount
Notebook 3 136.50
Pen 10 100.00
Calculator 1 799.00
Total 1035.50

Practical applications

  • Printing reports and tables in console tools
  • Logging messages while debugging
  • Reading options from args, for example a file name passed on the command line

Best practices

  • Keep one public class per file, named after the file.
  • Use printf for aligned output and + only for simple messages.
  • Write comments that explain why, not what the code obviously does.

Common mistakes

Misspelling the main method

Avoid

public static void Main(String[] args)

Prefer

public class Main {
public static void main(String[] args) { }
}

Java is case-sensitive. With Main the class compiles, but the launcher reports that no main method was found.

Forgetting the newline in printf

Avoid

System.out.printf("Total: %d", total);

Prefer

System.out.printf("Total: %d%n", total);

printf never adds a newline by itself, so the next output continues on the same line.

Important notes

  • Since Java 21 there is a preview feature allowing a simpler void main() without a class; this course uses the standard form that works on every current JDK.
  • %n is preferred to \n in printf because it produces the correct line ending for the platform.

Key takeaways

  • Execution starts at public static void main(String[] args).
  • println adds a newline; print doesn't; printf formats with placeholders.
  • Java is case-sensitive and every statement ends with a semicolon.

Try it yourself

  1. 1
    Print a 3-line address label using printf with fixed column widths.
  2. 2
    Print the result of "5" + 5 + 5 and 5 + 5 + "5" and explain the difference.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

3 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhich is a valid entry point for a standard Java program?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this topic