Video lecture
Watch on YouTube(opens in a new tab)Sub topic 1
How Java Runs: Bytecode and the JVM
Java is a programming language: a way to write instructions a computer can follow. What makes Java special is how it runs your code. You do not write instructions directly for one computer. Instead, you write for the Java Virtual Machine (JVM), a program that runs Java code on any computer.
Here is the flow:
Your .java files are source code, the text you write. A compiler is a program that translates your source code into bytecode, a compact set of instructions stored in .class files. The JVM then reads that bytecode and runs it. This is why Java is called portable: one compiled program can run on Windows, Mac, or Linux, wherever a JVM exists.
Anatomy of a Java Program
Every Java program lives inside a class, which is a container for code. The starting point is always the main method, a block of instructions the JVM runs first:
public class Main {
public static void main(String[] args) {
System.out.println("Java is running!");
}
}System.out.println(...) prints a line of text to the screen. The file must be saved as Main.java, matching the class name.
Variables and Types
A variable is a named box that stores a value. In Java, every variable has a declared type, which says what kind of value it holds:
int age = 30;
String name = "Sam";
System.out.println(name + " is " + age);int stores whole numbers. String stores text. Other common types are double for decimals and boolean for true/false.
Operators and Expressions
An operator is a symbol that does work on values, like +, -, *, and /. An expression is any combination of values and operators that produces a result:
int total = 5 * 4 + 2; // 22
System.out.println(total);The + symbol also joins text: "Hi, " + "Java" gives "Hi, Java".
Exercise
What does the compiler produce from a .java file?
Show answer
Bytecode, stored in a .class file, which the JVM runs.
Exercise
What will System.out.println("2" + 3); print?
Show answer
23. When one side is text, + joins them instead of adding numbers.