How Java Reads and Executes Instructions Step by Step

UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 1.2 Free with a free account

How Java Reads and Executes Instructions Step by Step

Data Structures and Algorithms · Chapter 1: Getting Started with JavaSection 1.2 · lesson 2 of 8714 min · free with a free account

← Installing, Configuring, and Running Your First Java ProgramNext lesson: Automating Repetitive Tasks Using Conditional Looping Mechanisms →

Earn 3 college credits for Data Structures and AlgorithmsRecommended for credit by NCCRS · Computer Science 251 · self-paced · one payment, lifetime access

In this lesson

Follow Java code from bytecode through variables, operators, decisions and input.

  • Explain how javac produces bytecode and how the JVM runs it on any system
  • Predict the results of integer division, overflow, casts, precedence and string joining
  • Trace variable values and choose between else-if chains and switch statements
  • Read keyboard input with Scanner and avoid the leftover end-of-line trap

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 (2,066 words). Read along, or search it.

Opening Question

From Typed Age to Ticket Price

A ticket booth program asks your age, and whether you're a student. Then it prints a price. Between your typing and that price, Java does a lot. Your text gets translated. Values are stored and combined, a path is chosen, and the user is asked for input. Here's that journey, one instruction at a time.

How It Works

Compiler, Bytecode and the JVM

The file you write, like Hello dot java, is source code. It's meant for people, and a processor can't read it directly. So Java works in two steps. First, the compiler, java c, checks the whole file against the language's rules. If it passes, java c writes bytecode: compact instructions for an imaginary machine, in a dot class file beside the source. Second, the java command starts the Java Virtual Machine, the JVM. It loads the bytecode, checks it for safety, and carries it out. While it runs, the JVM also spots instructions that repeat often, and translates those into the real machine's own instructions, so they run faster.

Key Idea

One Class File on Every System

Why the extra step? Think of a recipe written in a shared shorthand. Any kitchen with a chef who reads that shorthand can follow it. Bytecode is the shorthand, and the JVM is the chef. Windows, macOS and Linux each have their own JVM, so one class file runs on all three, without recompiling. And because java c checks first, many mistakes, like a misspelled keyword, are caught before anything runs. Mistakes that only show up while running come in lesson one point four.

Definition

Variables Have a Name, Type and Value

A variable is a named spot in memory that holds one value. It has a name you choose, a type, and the value it holds right now. The type is fixed when the variable is declared, and it never changes. Single quotes hold exactly one character. Double quotes hold text of any length. Declaring creates a variable with a type. Assigning stores a value, like age equals twenty-one. Initializing does both, on one line. Run it: Asha, twenty-one, A. The assignment replaced the value, and kept the type.

Constants

Final Values and Naming Conventions

Final makes a constant: a value that can never change. By convention, a constant's name is in capitals, like TAX RATE. Change it anyway, and the compiler refuses: cannot assign a value to final variable, TAX RATE. Other names use camel case, like total price. And names are case-sensitive, so score, and Score with a capital, are two different variables.

Data Types

Eight Primitive Types Plus String

Java has eight primitive types, which hold simple values directly. Four hold whole numbers: byte, short, int and long, from eight bits up to sixty-four. Int is the everyday default. It reaches about two point one billion, either way. Long reaches about nine quintillion, and its literals end with an L. Float and double hold decimals. Double is the default, good to about fifteen significant digits. Char holds one character, and boolean holds just true or false. String isn't a primitive, but it's a ready-made type you'll use constantly.

Common Surprises

Overflow, Inexact Decimals and Integer Division

Numbers live in a fixed number of bits, and that causes three behaviors worth knowing. Run this, and take the output one line at a time. First, an int that passes its largest value doesn't raise an alarm. It wraps around, to minus two point one billion. Second, decimals are stored in binary, so many are only approximate. Point one plus point two isn't exactly point three. So never compare two doubles with two equals signs. Third, dividing two whole numbers gives a whole number. Seven over two is three: the fraction is thrown away. Make either side a double, and the decimals stay: three point five. A cast to double on the seven does the same. A cast to int cuts off the decimals, and doesn't round: three point nine becomes three. And a remainder takes the left side's sign: minus seven mod three is minus one.

Type Conversion

Casting From Double to Int

Java converts on its own when nothing can be lost, like an int into a double. The other way, double to int, would lose the decimals. So without a cast, the compiler refuses: possible lossy conversion from double to int. Write the cast, int in parentheses, and you've said you accept the loss. Now it compiles, and prints nineteen.

Operators

Expressions, Comparisons and Shortcuts

An expression is anything that produces a value: a literal like forty-two, a variable, or several joined by operators. Arithmetic you know. Relational operators compare, and always give true or false. Logical and, or, and not combine those answers. Plus equals is a shortcut: n plus equals four means n equals n plus four. And plus plus adds one. i plus plus uses the current value, then increases it. Plus plus i increases first. Alone on a line, they do the same thing.

Evaluation Order

Operator Precedence Step by Step

When an expression has several operators, Java doesn't simply read left to right. It follows precedence: multiplication and division before addition. So three times four goes first, then six over three. That leaves two plus twelve minus two. Plus and minus tie, so they go left to right: twelve. Conditions work the same way. Arithmetic first: two plus two is four. Then the comparisons: five greater than three is true, four equals five is false. Not false is true. And has a higher rank than or, so true and false gives false. Then false or true gives true. Run it: twelve, true. Parentheses always win, so use them whenever an expression is hard to read.

Key Rule

Short-Circuit And and Or

And and or are lazy. If the left side of and is false, the whole thing must be false, so the right side never runs. Here d is zero, and d not equal to zero is false. So Java never tries a hundred over d. It prints false, safely. Swap the two halves, and the division runs first. Dividing an int by zero stops the program: arithmetic exception, divide by zero. Or works the same way: once its left side is true, the right side is skipped. That's how a quick test guards a risky one.

String Joining

When Plus Joins Text

Plus has a second job. When either side is a String, it joins text instead of adding. And plus works left to right, so where the first String sits matters. Total, then two, then three: the text comes first, so the numbers are joined. Twenty-three. Two plus three, then text: the numbers are added first, giving five total. Parentheses go first, so total, then two plus three in parentheses, gives total five.

Quick Check

Predicting a Mixed Plus Expression

Quick check, with a new line of code. One, plus two, plus the text three, plus four, plus five. What does it print? Pause, and predict. It prints thirty-three, forty-five. Left to right: one plus two is three, still a number. Then the text three is joined, making thirty-three. From there, everything is text, so four and five are joined, not added. Fifteen would add everything, and three thirty-nine would add the four and five.

Worked Example

Tracing Variables Line by Line

Unless something redirects it, a program runs sequentially: it finishes one statement, then moves to the next. The values in its variables are its state. To understand a program, trace it. Act like the JVM, one line at a time, and record every variable after each line. x is four. y is x times two: eight. x equals x plus y. Java reads the old x, four, adds eight, and stores twelve. y times two is sixteen. x over five is twelve over five, integer division: two. So y is fourteen. x plus equals three makes fifteen. And the program prints fifteen, comma, fourteen. Each assignment changed exactly one variable.

Common Mistake

Swapping Two Values With Temp

Every assignment destroys the old value, so the order of lines matters. Try to swap a and b directly. A equals b makes a three, and the original seven is gone. Then b equals a copies that three back. Both hold three. The fix is a third variable. Save a in temp first, then a gets b, and b gets temp. Now it prints three, seven.

Decisions

If, Else and Else-If Chains

A decision lets a program choose which statements run, based on a condition: any expression that's true or false. If the condition is true, its block runs. Otherwise the else block runs, never both. Always use braces, even for one statement. With more than two outcomes, chain the tests. Java checks them top to bottom, and runs only the first true one. A score of eighty-five gets a B. So order is part of the logic. Put the lowest threshold first, and a ninety-five gets a C, because seventy or more is true first.

Worked Example

Testing the Leap-Year Rule

And, or and not build one condition from several. The leap-year rule: divisible by four, and not by a hundred, or divisible by four hundred. Nineteen hundred is divisible by four, but also by a hundred, so the first group is false. It isn't divisible by four hundred either. False. Two thousand also fails the first group, but it is divisible by four hundred. True.

Switch Statement

Matching One Value Against Cases

When one variable is compared with a list of exact values, a switch is often clearer. Java jumps straight to the matching case: day two is Tuesday. Break ends the switch. Default handles any value that matches no case. Since Java fourteen, there's also an arrow form. It gives the switch a value, and needs no break.

Common Mistake

Fall-Through and Allowed Switch Types

In the older colon form, forgetting break causes fall-through. Execution starts at the matching case, and keeps going into the next ones. Level two starts at M, falls into H, and stops at the break. It prints M, then H. And switch doesn't accept every type. It takes int, char, String and a few more, but not double: selector type double is not allowed. So use switch for one variable against exact values. Use if and else if for ranges, for combined conditions, and for doubles.

Quick Check

Totaling Points With Fall-Through

Quick check. This switch adds points to a total, and n is two. Notice which cases have a break. What total does it print? Pause, and predict. It prints one hundred ten. Case two adds ten, and with no break, execution falls into case three, which adds a hundred, and then breaks. Ten forgets the fall-through. A thousand one hundred ten would also fall into default, but the break after case three stops it first.

User Input

Reading Input With Scanner

So far, every value was written into the program. Real programs ask the user, and Java's ready-made reader for that is Scanner. Import it at the very top of the file. Then create one connected to the keyboard. Treat that line as a fixed phrase for now. Each reading method reads one value. Next int reads a whole number, next double a decimal, and next one word. Next line reads everything up to the end of the line, and next boolean reads true or false.

Worked Example

Ticket Booth Pricing Logic

Here's the ticket booth. A ticket starts at twelve dollars, unless a test changes it. Under twelve pays six, sixty-five or over pays eight, and other students pay nine fifty. Run it, type thirty, and answer yes. Nine fifty. Run it again, for someone who is seventy: eight, because the age test comes first. Percent point two f prints exactly two digits after the point, and percent n ends the line. And to compare text, use dot equals. Two equals signs don't reliably compare what two pieces of text say.

Common Trap

The Leftover End-of-Line After NextInt

One trap catches almost everyone. When you type three and press Enter, the keyboard sends the digit and an end-of-line. Next int takes only the digit, and leaves the end-of-line behind. So the next line call finds it, reads an empty line, and returns at once. Run it: the program never waits for the name. The booking is for an empty string. The fix: one extra next line call, to discard the rest of the number's line. Now it waits, and books three for Asha. The same trap follows next double. Two next calls, or two next line calls, don't have it.

Key Takeaways

From Bytecode to Clean Input

To sum up. Java c compiles source into bytecode once, and the JVM on each machine runs it. A variable is a named, typed spot in memory. Watch out for overflow, inexact decimals, and integer division. Precedence decides the order, and and or stop as soon as the answer is known. An else-if chain runs the first true branch, so order matters. And after next int, clear the line before next line.

Think About It

NextDouble Followed by NextLine

Something to think about. A program reads a price with next double, then a product name with next line. What will the user see, and where exactly does the fix go?

About Data Structures and Algorithms at UPI Study

Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. 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: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms

Why take it here

Why students take Data Structures and Algorithms with UPI Study

How programs store and search dataData Structures and Algorithms teaches how to organize data and measure how fast code runs: arrays, linked lists, stacks, queues, trees, heaps, hash tables, sorting and graphs, all written in Java. It is a core course in computer science and software 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

Data Structures and Algorithms 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 How Java Reads and Executes Instructions Step by Step

Why does 7 / 2 equal 3 in Java?
Dividing two int values in Java gives an int, so the fractional part is thrown away and 7 / 2 is 3. To keep the decimals, make either side a double, as in 7.0 / 2 or (double) 7 / 2, which both give 3.5. A cast to int also truncates rather than rounds, so (int) 3.9 is 3, and a remainder takes the left side's sign, so -7 % 3 is -1.
What is short-circuit evaluation in Java?
Short-circuit evaluation means && and || stop as soon as the answer is known. If the left side of && is false, the right side never runs, and if the left side of || is true, the right side is skipped. That lets a quick test guard a risky one: with int d = 0, d != 0 && 100 / d > 5 safely gives false, while reversing the halves throws an ArithmeticException.
What does System.out.println(1 + 2 + "3" + 4 + 5) print?
It prints 3345. Java evaluates + from left to right, so 1 + 2 is first added to make the number 3, and joining the String "3" gives the text 33. From that point the expression is text, so 4 and 5 are joined rather than added. Parentheses change the result: "total " + (2 + 3) prints total 5, because the parentheses are evaluated first.
Why does nextLine return an empty string after nextInt?
nextInt reads only the number and leaves behind the end-of-line produced by the Enter key. The next nextLine call finds that leftover end-of-line, returns an empty string at once, and never waits for the user. The fix is one extra nextLine call right after nextInt to discard the rest of that line. nextDouble has the same trap, while two next calls in a row do not.

About the Data Structures and Algorithms course

How many college credits is Data Structures and Algorithms?
Data Structures and Algorithms (Computer Science 251) 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 Data Structures and Algorithms cost and what is included?
$250, paid once, with lifetime access: all 87 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 Data Structures and Algorithms take?
It is self-paced with no deadlines. The 87 lessons total about 15 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 Data Structures and Algorithms.

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

Data Structures and Algorithms
3 credits · NCCRS
Enroll →