Setup, the JVM, and your first program
What actually happens when Java runs, and writing the first program from an empty file.
Finished reading?
Mark this session so you can track where you are.
What actually happens when Java runs, and writing the first program from an empty file.
Finished reading?
Mark this session so you can track where you are.
Before we write a single line of Java, it is worth answering a plain question: when you run a program, what actually happens? You typed some text into a file. Somehow that text turns into a running program. Java does this in a particular way, and once you see the shape of it, everything later in the course will sit on solid ground.
.java file to a running program.JDK, JRE, and JVM apart, and say which one you install.You have already met two ways a program can run, even if no one named them for you. In Python, you hand your .py file straight to the python command and it starts doing what you wrote, line by line, right away. In C, you first run a compiler that turns your .c file into a finished program, a real executable, and then you run that. Two different styles. Java picks a third path that borrows from both.
In Java, the source code you write lives in a file ending in .java. You do not run that file directly, and it does not get turned into a finished program for your specific computer either. Instead it goes through two steps.
javac (the Java compiler) reads your .java file and translates it into a new file ending in .class. The contents of that file are called bytecode. Bytecode is not human-friendly text, and it is not your computer's native instructions either. It is an in-between language, designed for one specific imaginary machine that we will meet in a moment.java launcher starts up the JVM (the Java Virtual Machine) and feeds it the .class bytecode. The JVM reads the bytecode and carries out the instructions, which is what makes your program actually do things on screen.So the journey is: Hello.java goes into javac, out comes Hello.class, and the JVM runs that. Source becomes bytecode becomes behavior.
Here is the payoff. Your .class bytecode is the same on every kind of computer. The same bytecode file runs on Windows, on a Mac, and on Linux, without being rebuilt. The only thing that differs between those machines is the JVM itself: there is a Windows JVM, a Mac JVM, a Linux JVM, and each one knows how to turn the same bytecode into instructions for that particular system. This is the famous Java promise: write once, run anywhere.
You compile your Java once, into bytecode. That one bytecode file then runs on any machine that has a JVM. The JVM is the part that is different per platform, so your code does not have to be.
javac compiles to bytecode, then a per-platform JVM runs that bytecode.These three letters get thrown around constantly and are easy to mix up. They are not three competing things; they are three nested layers, each containing the one before it. Let us define them from the inside out.
javac, the compiler. This is the full kit. If you are writing Java, this is what you install.JVMJREJDKjavac and friends). Enough to write, compile, and run. Install this one.JDK contains the JRE, and the JRE contains the JVM. To learn Java, you install the JDK, because it is the only one of the three that can both compile your code and run it.
JVM, the engine. Put it inside a bigger box with spare parts and you get the JRE, which can run things. Put that inside the biggest box, which also holds the tools to build, and you get the JDK. You buy the biggest box.Java is often introduced through a list of adjectives, sometimes called its buzzwords. They are not marketing fluff; each one names a real design choice. You do not have to memorize the list, but skimming it now tells you what kind of language you are learning and why it behaves the way it does.
Time to meet actual Java. Below is the smallest complete program that prints a line. Read it once slowly, then press Run. Do not worry yet about understanding every word; we will take it apart piece by piece right after.
public class Main { public static void main(String[] args) { System.out.println("Hello, world."); }}Hello, world.
That is it. The whole thing prints one line: Hello, world. There is a lot of ceremony around that single useful line, and that ceremony can feel like noise at first. It is not noise; every word is doing a real job. Let us name them one at a time.
public class MainEvery piece of Java code lives inside a class. For now, treat a class simply as a named container that holds your code; it is the box your program lives in. Here the box is named Main. The word publicin front means “this box can be seen from outside”, which is what lets the java launcher find it and start it. The curly braces { and } mark where the box begins and ends, the way indentation marks a block in Python.
classin the lightest possible way here, just “a container for code”. The real meaning of a class, and why Java is built around them, is the heart of this course. We get there properly in creating classes and objects. Until then, you can copy this wrapper without fully understanding it.public static void main(String[] args)This line is the one to slow down on. When you run a Java program, the JVM looks for one specific method to begin at, and that method must be spelled exactly like this. A method is a named block of code that does a job, much like a function in Python or C. This particular method is named main, and it is special only because the JVM has agreed in advance to start there. If you misspell it, the program will compile but refuse to start, because there is no front door.
Now the four words wrapped around main. Here is what each one means, in plain terms.
public: visible from outside this class, so the launcher is allowed to call it. Same idea as the public on the class.static: this method belongs to the class itself, not to any particular object made from it. That is why the JVM can call main without first creating anything. The full weight of this word will only make sense once you know what an object is.void: this method hands nothing back when it finishes. A method can compute a value and return it; voidis how you say “this one returns nothing, it just does its work and stops”.String[] args: a place for any extra words you might type after the program's name when you launch it from a terminal. The String[]part means “a list of pieces of text”. You will rarely touch this early on; it just has to be present in the signature.static and void, point at ideas we have not built yet. That is completely fine. For now, accept this exact line as the fixed phrase that means “start here”, the same way you accept def main(): conventions without questioning them. The real meaning of void and return values arrives in methods, and static gets its own treatment in the static and final keywords. Forward-references like this are deliberate; we never explain a thing before you have what you need to understand it.System.out.println(...)Inside main is the one line that actually does something visible. System.outrefers to the program's standard output, which is the screen, the same destination Python's print and C's printf write to. The .printlnpart means “print this line and then move to a new line”. Whatever you put in the parentheses between the quotation marks is the text that appears. Anything inside double quotes is just literal text, called a string, and Java prints it as-is.
First, Java is strict about ;at the end of a statement. The semicolon is how you tell Java “this instruction is finished”. Forgetting it is the single most common first error. Python let you skip it; Java does not. Second, the text must be wrapped in straight double quotes,"like this", not single quotes and not curly typographic quotes. Single quotes mean something different in Java, which you will meet later.
A program can do more than one thing. Each statement runs in order, top to bottom, exactly as written. To print three lines, you simply write three print statements, one after another. Run this and watch the output appear in the order the lines are written.
public class Main { public static void main(String[] args) { System.out.println("Welcome to Java."); System.out.println("This is your first program."); System.out.println("Let us begin."); }}Welcome to Java. This is your first program. Let us begin.
Three statements, three lines of output, in the same order you wrote them. This top-to-bottom flow is the bedrock everything else builds on. Later you will learn to make the program choose between paths and repeat work, but underneath, statements still run one after another unless you say otherwise.
println moves to a new line after printing, so each call starts fresh on its own line. There is also a plain print that does not add the new line, so several print calls would run their text together on one line. We will lean on both once we start building output more carefully in variables, types, and input/output.Let us put the pieces together into one mental picture you can carry for the rest of the course. When you ask a Java program to run, this is the sequence.
.java file, inside a class, with a main method as the starting point.javac compiles that source into a .class file full of bytecode.java launcher starts the JVM and hands it the bytecode.main, runs the statements inside it in order, and your output appears.Every Java program you ever run, from this three-line greeting to a program with thousands of classes, follows exactly this path. You now know what the words mean and what happens when you press Run. That is the foundation. Everything from here on is filling in what goes inside main.
In this course you press Run and the playground handles the two steps for you. On your own machine, you would do those two steps by hand in a terminal, and it is worth seeing exactly what they look like so the words javac and java feel concrete.
HelloWorld.java.javac HelloWorld.java. If there are no errors, this produces HelloWorld.class, the bytecode.java HelloWorld (note: no .class, no .java, just the class name). The JVM starts, finds main, and your output appears.$ javac HelloWorld.java # compile: source -> bytecode$ java HelloWorld # run: the JVM executes the bytecodeHello, World!A sample terminal session. javac produces HelloWorld.class, then java runs it.
javac [options] [filename]. The filename is the .java file you want to compile; the options tune how it builds. For now you will only ever need the plain form,javac YourFile.java, with no options at all.A comment is text the compiler ignores completely. It is there for humans: to explain a tricky line, to leave a reminder, or to temporarily switch off a line of code. Java has two kinds, and they work just like the comments in C.
//. Everything from there to the end of that line is ignored./* and ends with */. Everything between them is ignored, even across many lines.public class Main { public static void main(String[] args) { // This is a single-line comment. Java ignores it. System.out.println("This line runs."); /* This is a multi-line comment. It can span several lines. None of this is run. */ System.out.println("So does this one."); }}This line runs. So does this one.
Java cares about a handful of small, mechanical rules at the level of individual characters and words. These are sometimes called lexical rules. Getting them wrong produces most first-week errors, so it is worth naming them once, clearly, so you recognize the mistakes when they happen.
;. A missing or misplaced semicolon is the single most common beginner error.count and Count are two completely different names. main must be lowercase; Main would not be found as a starting point.class, public, static, and void have fixed meanings, so you cannot use them as names for your own variables or methods._, or a $, and after that may also contain digits. So score1 is fine, but 1score is not.Almost every error you hit in your first week comes from one of these: a forgotten ;, a capital letter where you meant lowercase, or a name that clashes with a keyword. When the compiler complains, glance back at this short list first. Nine times out of ten the fix is here.
Try each one yourself first, then open the answer.
.java source and a running program, and say which tool does each.JDK, JRE, and JVM, which one do you install to learn Java, and why that one?public static void main(String[] args). What does void tell us about main?println statements, what would change in the output?total, 2nd, _count, class, userName? Say why each is or is not.// comment and a /* ... */ comment? When would you reach for each?Take these away. They continue exactly what we just did.
Hello, world. Run it and confirm the output matches..java file to output on screen, labelling where javac, the .class file, and the JVM each appear. Keep it for your notes; you will refer back to it.