Course outline · 0% complete

0/29 lessons0%

Course overview →

Your first Java program

lesson 1-1 · ~6 min · 1/29

Welcome to Java

You know Python basics, so you already understand variables, loops, and functions. Java expresses the same ideas with more structure — and that structure is why it runs so much of the serious world: Android apps, bank and airline backends, and most large company codebases. Teams of hundreds can work on one Java program because the compiler checks everyone's code against everyone else's before anything runs. Two big differences up front:

  1. Everything lives inside a class. A class is a named container for code. Even a one-line script needs one.
  2. Java is compiled and statically typed. You declare the type of every variable, and a compiler checks your whole program before it runs.

In Python you print with print("hi"). In Java the same idea takes a few more lines, and every one of them has a job. Let's look at the smallest complete Java program.

Code exercise · java

Run this program. It should print one line. Do not change anything yet, just press Run and read each line of the code while it executes.

Anatomy of the program

  • public class Main { ... } declares a class named Main. The file is named after it (Main.java). All your code sits inside its braces { }.
  • public static void main(String[] args) is the main method. Java starts every program by searching for a method with exactly this signature — change one word and the program will not launch. Each keyword has a precise meaning (unit 4 decodes them all); until then, copy the line exactly.
  • System.out.println("Hello, Java!"); prints a line of text. It is Java's print().
  • Every statement ends with a semicolon ;. Python uses line breaks, Java uses semicolons.
  • Braces { } group code the way indentation does in Python. Java ignores indentation, but you still indent for humans.

Misspell main or drop a semicolon and the program will not even start. The compiler reports the mistake first.

Quiz

Your file declares public class Main. What must the file itself be named?

Quiz

In Python you write print("hi") at the top of a file and it runs. Why can't you do that in Java?

Code exercise · java

Your turn. Make the program print exactly two lines: first `Ada Lovelace`, then `learning Java`. You will need two println statements.