Jack Ng

Essay

Learning Java, Part 1: From Python to Java

Study notes on what the JDK is, how source becomes bytecode, the anatomy of a first program, and the three ideas behind object-oriented programming. Written entirely by an AI model.

This is the first of seventeen parts. Parts 1 to 16 follow the chapter order of Herbert Schildt’s Java: A Beginner’s Guide (sixth edition), which a past CITS2005 lecture slide appears to cite as the unit textbook. They cover every chapter, including the GUI ones the unit is unlikely to examine. Part 17 covers testing and documentation, which the unit assesses but the book leaves out. The series assumes you already know a little Python, as covered in the Learning Python series, and points out where Java behaves differently.

The book was written for Java 8. Every example here was run on a current JDK, and a Modern Java note marks the places where the language has since moved on.

What you install

Python ships one program, python, that reads your source and runs it. Java splits the job in two:

  • javac, the compiler, reads Kettle.java and writes Kettle.class, a file of bytecode.
  • java, the launcher, starts the Java Virtual Machine (JVM), which loads the bytecode and runs it.

Both come in the JDK (Java Development Kit). Any JDK from version 21 onwards is fine for this series; on a Mac, brew install openjdk works.

Bytecode is the same on every operating system, and each platform has its own JVM. That is the origin of the old slogan “write once, run anywhere”. The JVM also checks bytecode before running it and translates the busy parts into machine code as the program runs (just-in-time compilation), so Java is usually much faster than Python for the same loop.

A first program

public class Kettle {
    public static void main(String[] args) {
        System.out.println("The kettle is on.");
    }
}
The kettle is on.

Save it as Kettle.java, then:

javac Kettle.java     # writes Kettle.class
java Kettle           # runs it; note: no .class on the end

Since Java 11 you can also run a single file directly with java Kettle.java, which compiles in memory first. That is handy for small experiments.

Line by line:

  • public class Kettle declares a class. All Java code lives inside a class. A public class must be in a file of the same name, matching case exactly: Kettle goes in Kettle.java.
  • public static void main(String[] args) is where the program starts. public lets the JVM call it, static means no object is needed to call it, void means it returns nothing, and args holds any command-line arguments.
  • System.out.println(...) prints and adds a newline. System.out.print(...) prints without one.
  • Every statement ends with a semicolon. Blocks are marked with braces, not indentation. Indent anyway, because people read your code.

Variables have declared types

In Python a name can point at anything. In Java you declare the type of a variable before you use it, and the compiler holds you to it.

public class TeaOrder {
    public static void main(String[] args) {
        int cups;          // declare
        cups = 3;          // assign
        double price = 4.5; // declare and assign together
        System.out.println("Cups: " + cups);
        System.out.println("Total: " + cups * price);
    }
}
Cups: 3
Total: 13.5

int holds whole numbers and double holds numbers with a fractional part. + between a string and anything else joins them into a string. Part 2 covers all eight basic types.

Assigning a value of the wrong type is a compile-time error: cups = "three"; never gets to run. Python would only find that mistake when the line ran. This is the biggest change in habit: you will see many more errors, but you see them earlier.

Two control statements, briefly

Part 3 covers control flow properly. These two are enough to write small programs straight away:

public class Litres {
    public static void main(String[] args) {
        for (int gallons = 1; gallons <= 3; gallons++) {
            double litres = gallons * 3.7854;
            System.out.println(gallons + " gallons is " + litres + " litres");
            if (gallons == 2) System.out.println("  (that fills the big pot)");
        }
    }
}
1 gallons is 3.7854 litres
2 gallons is 7.5708 litres
  (that fills the big pot)
3 gallons is 11.356200000000001 litres
  • The condition of an if goes in parentheses. A single statement needs no braces, but adding them is safer.
  • for (start; condition; step) replaces Python’s for i in range(...). gallons++ adds one.
  • The last line shows that double arithmetic is approximate, just as Python floats are.

Identifiers and keywords

Names may contain letters, digits, _ and $, cannot start with a digit, and are case sensitive. Java has about fifty reserved keywords (class, public, int, if, new, this and so on) that cannot be names. Convention matters to readers and markers:

Kind Style Example
class, interface UpperCamelCase TeaOrder
method, variable lowerCamelCase totalPrice
constant UPPER_SNAKE_CASE MAX_CUPS
package lowercase com.example.cafe

Three kinds of error

  • Compile errors come from javac: a missing semicolon, an undeclared variable, a type mismatch. Read the first message first; later ones are often caused by it. The message names the file and line, then shows a caret under the problem.
  • Runtime errors are exceptions thrown while running, such as dividing an int by zero (ArithmeticException). Part 9 covers them.
  • Logic errors compile and run but give the wrong answer. Only testing finds them.

Object-oriented programming in one page

Java was designed around objects from the start. The book introduces three ideas that every later part builds on:

  • Encapsulation: an object keeps its data private and offers methods to use it. Code outside cannot put the object into a broken state.
  • Inheritance: a class can extend another and reuse its fields and methods, adding or changing only what is different.
  • Polymorphism: one interface, many implementations. Code written for a Shape works for any kind of shape, and each shape decides how to compute its own area.

Python has all three as well. What changes is that Java checks them at compile time, which is why so much of CITS2005 is about designing types.

The class library

Java comes with thousands of ready-made classes, grouped into packages. System, String and Math are in java.lang, which every program can use without importing anything. Others need an import, such as import java.util.Scanner;. Part 8 covers packages.

Modern Java. From JDK 25, a small program can skip the class declaration entirely (void main() { IO.println("hi"); }), which is meant for beginners. University courses and exams still use the full form shown above, so learn that first.

Exam-style checks

  • Explain the difference between javac and java, and say what a .class file contains.
  • Why must public class Kettle be saved as Kettle.java?
  • Explain each word of public static void main(String[] args).
  • Name one error Java catches at compile time that Python only catches at runtime.

Where to practise

There are no Java drills on this site yet. Install a JDK and type every example in rather than copying it, because the compile errors you make along the way are the lesson. Chapter 1 of Schildt ends with a self test and two “Try This” exercises (a gallons-to-litres converter and a conversion table) that are worth doing. For quick experiments, jshell (included with the JDK) lets you type Java one line at a time, much like the Python prompt.