Your first program: how a Java file is built
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
A small program
Here is a program that uses command-line arguments, prints a few lines and does a little arithmetic. Save it as Main.java.
public class Main {
public static void main(String[] args) {
// A single-line comment
System.out.println("Welcome to Java");
/* A comment that
spans several lines */
String name = args.length > 0 ? args[0] : "friend";
System.out.println("Hello, " + name + "!");
int hours = 8;
int days = 5;
System.out.println("Weekly hours: " + hours * days);
System.out.print("No new line here. ");
System.out.println("Now there is one.");
System.out.printf("Pi is about %.2f%n", Math.PI);
}
}
Run it with java Main.java, and then with java Main.java Sara. The second run passes "Sara" as the first argument.
Reading it line by line
public class Main declares a class called Main. In Java, all code lives inside classes. public means other code can see it. By convention, class names start with a capital letter and use CamelCase: Main, BankAccount, OrderService. If a class is public, its file must have the same name plus .java.
The curly braces { } mark where a block of code starts and ends. Everything between the braces after the class name belongs to the class.
Next comes the entry point:
public static void main(String[] args)
Every word has a meaning. public: the JVM must be able to call it. static: it belongs to the class, not to an object, so the JVM can call it without creating one. void: it returns nothing. main: the name the JVM looks for. String[] args: an array of the command-line arguments. You do not need to understand all of it yet. For now, treat it as the fixed opening you copy for every program. We explain each part when we reach classes and methods.
Inside main, each line is a statement, and each statement ends with a semicolon. Forget one and the compiler will tell you.
System.out.println(...) prints text and ends the line. System is a class, out is its static field for standard output, and println is a method. print does the same without the line break. printf prints formatted text. %.2f means a floating-point number with two decimals, and %n is a platform-independent line break.
The line with args.length > 0 ? args[0] : "friend" uses the ternary operator: if there is at least one argument, use the first, otherwise use "friend". Array positions start at 0.
In "Weekly hours: " + hours * days, Java does the multiplication first, then joins the result to the text. Operators have an order of precedence, like in maths. If you want text and addition mixed in a different way, use brackets.
Comments
A comment is ignored by the compiler. Use // for one line and /* ... */ for several lines. There is also a documentation comment that starts with /**, used by the Javadoc tool to generate documentation. Write comments to explain why you did something. The code already shows what it does.
Case and spelling
Java is case-sensitive. String is a class and string is nothing. System with a capital S is required. These errors give messages such as "cannot find symbol". When you see that, check the spelling and the capital letters first.
Naming conventions
| What | Style | Example |
|---|---|---|
| Classes, records, interfaces | UpperCamelCase | OrderService |
| Methods and variables | lowerCamelCase | totalPrice |
| Constants | UPPER_SNAKE_CASE | MAX_RETRIES |
| Packages | lowercase | com.example.shop |
The compiler does not force these, but every Java developer expects them. Following them makes your code easier for others to read.
Common mistakes
- Missing semicolon or brace. The error often points to the line after the real mistake.
- Misspelling
mainor changing its signature. The JVM then reports that no main method was found. - Mixing up
printandprintln. Output gets squashed on one line. - Using single quotes for text.
'a'is one character. Text uses double quotes.
Try it yourself
- Change the program to print your name, your city and your favourite programming language on three lines.
- Pass two arguments and print both, in reverse order.
- Remove a semicolon on purpose and read the error message. Then misspell
Systemand compare the message.
public class Main {
public static void main(String[] args) {
// A single-line comment
System.out.println("Welcome to Java");
/* A comment that
spans several lines */
String name = args.length > 0 ? args[0] : "friend";
System.out.println("Hello, " + name + "!");
int hours = 8;
int days = 5;
System.out.println("Weekly hours: " + hours * days);
System.out.print("No new line here. ");
System.out.println("Now there is one.");
System.out.printf("Pi is about %.2f%n", Math.PI);
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account