What Java is and how it runs
Java is a programming language, but it is also a system for running programs almost anywhere. You write human-readable instructions called source code. A tool called the compiler translates them into bytecode, a compact intermediate format. The Java Virtual Machine (JVM) — a program on your computer — reads that bytecode and runs it. Because a JVM exists for Windows, Mac, Linux, and more, the same compiled Java program runs on all of them. That is Java's famous promise: write once, run anywhere.
Your first Java program
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}Save it as Hello.java. In a terminal, run javac Hello.java to compile, then java Hello to run. The text Hello, Java! appears on screen.
Every Java statement — one instruction — ends with a semicolon. Code lives inside classes (named containers for code), and the JVM always looks for a method named main to start your program.
Data: types, variables, and strings
Java knows the kind of data each piece of information holds. A primitive type is a simple built-in kind, such as int (whole numbers), double (decimals), and boolean (true or false). A variable is a named box that stores a value. Java converts types automatically only when no information is lost, like int into double; otherwise you must convert explicitly.
int count = 3;
double total = count * 2.5; // int becomes double safely
boolean done = total > 7.0;
String greeting = "Hi, " + "Java"; // joining text is easy
System.out.println(done); // prints trueA String is a piece of text, and + glues strings together.
Decisions, repetition, arrays, and methods
Programs make choices and repeat work:
int[] scores = {90, 75, 88}; // an array: numbered list of values
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= 80) {
System.out.println(scores[i] + " passed");
} else {
System.out.println(scores[i] + " retry");
}
}An array is a fixed-size list where each item has a number, starting at 0. An if statement chooses between paths; a for loop repeats.
A method is a named, reusable block of code you can call with different inputs:
static String describe(int score) {
return score >= 80 ? "passed" : "retry";
}Exercise
Why can the same compiled Java program run on different operating systems?
Show answer
Because each operating system has its own JVM, and every JVM understands the same bytecode. The JVM adapts the bytecode to its machine.
Exercise
What number does an array's first item have?
Show answer
Zero. Arrays are numbered starting from 0, so scores[0] is the first item.
Spotted a mistake, or code that does not work?