The Java Virtual Machine, Explained

UPI Study › Courses › Introduction to Operating Systems › Free lessons › Lesson 10.6 Free with a free account

The Java Virtual Machine

Introduction to Operating Systems · Chapter 10: Virtualization and Virtual MachinesSection 10.6 · lesson 83 of 839 min · free with a free account

← Setting Up VirtualBox

A free account plays all of Chapter 1 and 3 more lessons of Introduction to Operating Systems. Create a free account →

Earn 3 college credits for Introduction to Operating SystemsRecommended for credit by NCCRS · Computer Science 354 · self-paced · one payment, lifetime access

In this lesson

How Java bytecode runs anywhere on a stack-based virtual machine.

  • Explain how javac and the JVM make Java programs portable
  • Read simple JVM bytecode such as iload, iadd, and ireturn
  • Describe the class loader, verifier, interpreter, JIT compiler, and garbage collector
  • Distinguish the JVM from a system virtual machine

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,171 words). Read along, or search it.

Opening Analogy

Write Once, Run Anywhere

Imagine writing a letter once, and having it read perfectly in English, in Hindi, and in Spanish, with no rewriting. You'd need a translator sitting beside each reader. That's the idea behind Java's famous promise: write once, run anywhere. The translator is a virtual machine. But it's a different kind from the one you built in lesson 10.5. It doesn't run a whole operating system, only one program.

Core Idea

Bytecode for an Imaginary Computer

Normally, a program is built for one kind of machine. Its machine code speaks one processor's language, so software makers rebuilt and retested for every platform. Java adds a step. Its compiler, javac, doesn't make machine code for any one computer. It makes bytecode: compact instructions for an imaginary computer, stored in files ending in dot class. The Java Virtual Machine, the JVM, is a program written once for each platform. It pretends to be that imaginary computer, and carries out the bytecode. So a program is compiled once, and any computer with a JVM runs the same class file. The JVM doesn't even know the Java language. Kotlin and Scala compile to bytecode too.

Hands-On

Compiling and Running Hello

Here's a tiny real program, typed into a file called Hello dot java. In Java, the public class name must match the file name. main prints two lines. And a small method, add, returns the sum of two numbers. Compile it: javac, Hello dot java. javac prints nothing when it succeeds. ls shows the new file beside the source: Hello dot class, the bytecode. Now run it: java Hello. Not Hello dot class. The java command starts the JVM, and tells it which class to run. Two lines, printed by a JVM on this Mac.

Class Files

Class Format Version 65

What did javac make? The file command reads the first bytes of a file, and says what kind of file it is. Compiled Java class data, version 65: the class format of Java 21. It isn't machine code for this Mac's processor. That's the whole point. Nothing in it is tied to this machine, so the same file can travel.

Real Example

Same Class Files on Windows and Linux

Sam, who runs a small online bakery, wrote an order-checking program in Java, on a Windows laptop. Ivy, who looks after the computers at a school, wanted it on her Linux server. Do I need to rewrite it? Sam asked. Copy the class files, Ivy said, and make sure the server has a JVM. They ran java on the server, and the same lines appeared.

Reading Bytecode

A Stack Machine Adds 2 and 3

Now, what does bytecode look like? javap, a class file reader that comes with the JDK, prints it. Dash c means show the code. We pipe it through grep, to keep only the method add, and the five lines after it. The JVM is a stack machine. It keeps a pile of values, and each instruction pushes, pops, or combines the values on top. Follow add, of 2 and 3. iload_0 pushes the first argument, 2. iload_1 pushes the second, 3. iadd pops the top two, and pushes their sum, 5. And ireturn hands that 5 back to the caller. The letter i means integer.

Quick Check

Predicting the Bytecode for Twice

Quick check. Suppose we add one more method to Hello: twice, which returns a plus a. What bytecode will javac make for it? Pause, and predict. Two iload_0s, then iadd, then ireturn. twice has only one argument, a, so iload_0 pushes that same first argument twice. iload_1 would need a second argument, and twice has none. And iadd always takes two values off the pile, so a single load can't work. Let's check it on this Mac. Add the method, compile, and print its bytecode. There it is: iload_0, iload_0, iadd, ireturn.

JVM Parts

Loader, Verifier, Interpreter, JIT, Collector

When you type java Hello, several parts of the JVM wake up in order. Think of an airport: bags come in, they pass security, and then the plane flies. The class loader finds the class files a program needs, and brings them into memory, usually only when first needed. That includes library classes, like the one that prints. The bytecode verifier checks loaded code before it runs. It mustn't misuse the pile, jump to nowhere, or treat a number as an object. A damaged or tampered file is refused. The interpreter starts running bytecode at once, one instruction at a time. It's quick to start, but slow for work that repeats many times. So the JIT compiler, short for just-in-time, watches for methods that run again and again, the hot ones. It compiles them into this machine's own code, and then they run at full speed. And the garbage collector frees objects that no code can reach any more. You never call free, as in C. Lesson 4.11 shows how.

Quick Check

Which Method Gets Compiled

Quick check. A program calls one method, setup, just once. It calls another method, price, ten million times in a loop. Which one is the JIT compiler most likely to turn into machine code? Pause, and decide. price. It runs again and again, so it's hot. The JIT compiles it to this machine's code, and the loop runs at full speed. setup runs once, so interpreting it is cheapest: compiling it would cost more than it saves. And the JVM doesn't only interpret. That's a common mix-up.

Common Mix-Ups

Interpreted Myths and JVM Versus JDK

That mix-up is worth naming. People say Java is slow because it's interpreted. But only the first runs are interpreted, and the busy methods become machine code while the program runs. A second mix-up: the JVM and the JDK aren't the same. The JVM only runs bytecode. The JDK also holds javac, javap, and other tools.

Comparison

A Whole Computer Versus One Program

You've now met two meanings of virtual machine. They share one trick, a software layer that hides the real machine, but they solve different problems. A system VM pretends to be a whole computer. It runs a full guest operating system, and its layer is the hypervisor. The JVM pretends to be an imaginary computer for one program. It runs bytecode, and it's itself a normal process, using the host's system calls, from lessons 2.2 and 2.3. That's why the same bytecode is happy on a laptop, on a server, or inside a VM from lesson 10.5.

Key Takeaways

Bytecode and the JVM Reviewed

To recap. javac compiles Java into bytecode, stored in class files, for an imaginary computer. A JVM on each platform loads, verifies, interprets, and JIT-compiles that bytecode, so one class file runs anywhere. And bytecode runs on a pile: iload pushes, iadd adds the top two, and ireturn hands back the result.

Course Wrap-Up

Layers, Sharing, and Protection

And that's the end of this course. You started with a simple question: what does an operating system do? Since then, you've watched it share a processor among processes, keep threads from tripping over each other, and stretch a small memory into a big one. You've seen it manage disks, files, devices, and networks, and guard a computer from harm. And in this last part, you saw that the operating system itself can be pretended. The same few ideas keep coming back: hide the details behind a clean layer, share what is scarce, and protect what is precious. Keep exploring. Make a VM, break it, and roll it back.

About Introduction to Operating Systems at UPI Study

Introduction to Operating Systems (Computer Science 354) is a self-paced online course of 83 video lessons in 10 chapters, from what an operating system does and process scheduling to concurrency, memory, devices, file systems, networks, the internet, security and virtual machines. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Linux vs Operating Systems

Why take it here

Why students take Introduction to Operating Systems with UPI Study

What happens under every app you runIntroduction to Operating Systems explains the software that runs a computer: processes and scheduling, threads and synchronization, deadlock, memory and paging, devices and storage, file systems, networking, security and virtualization. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Introduction to Operating Systems carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About The Java Virtual Machine

What is Java bytecode?
Java bytecode is the set of compact instructions that the javac compiler produces for an imaginary computer, stored in files ending in .class. It is not machine code for any real processor, so the same class file can run on any computer with a Java Virtual Machine. Other languages, such as Kotlin and Scala, also compile to JVM bytecode.
How does the JVM run bytecode on a stack?
The JVM is a stack machine: each instruction pushes values onto a pile, pops them off, or combines the values on top. For a method that adds two integers, iload_0 pushes the first argument, iload_1 pushes the second, iadd pops both and pushes their sum, and ireturn hands the result back. The letter i marks integer instructions.
What does the JIT compiler do in the JVM?
The just-in-time, or JIT, compiler turns frequently run methods into the computer's own machine code while the program runs. The JVM begins by interpreting bytecode, which starts quickly but is slow for repeated work. When a method becomes hot, such as one called ten million times in a loop, the JIT compiles it so it runs at full speed. A method called once is usually cheaper to interpret.
What is the difference between the JVM and the JDK?
The JVM only runs bytecode, while the JDK, the Java Development Kit, also includes development tools such as the javac compiler and the javap class file reader. Inside the JVM, a class loader brings classes into memory, a verifier checks them, an interpreter and JIT compiler run them, and a garbage collector frees objects that no code can reach any more.

About the Introduction to Operating Systems course

How many college credits is Introduction to Operating Systems?
Introduction to Operating Systems (Computer Science 354) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Introduction to Operating Systems cost and what is included?
$250, paid once, with lifetime access: all 83 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Introduction to Operating Systems take?
It is self-paced with no deadlines. The 83 lessons total about 10 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Introduction to Operating Systems.

83 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Introduction to Operating Systems
3 credits · NCCRS
Enroll →