Java Introduction: Understand Your First Program
Java lets you describe information and the rules that work on it. Start by understanding what a program does, how it runs, and how to check its result. You do not need to memorize a page of unfamiliar syntax first.
What you will understand
- Explain Java without confusing it with JavaScript.
- Distinguish source code, bytecode, the JDK, and the JVM.
- Read the structure of a small Java program without memorizing every keyword.
- Predict printed results and separate text from calculations.
- Describe a program's inputs, processing, outputs, and limitations.
What is Java, in plain language?
Java is a programming language: a set of rules for expressing instructions a computer can carry out. You write those instructions in a source file, and Java tools turn them into a form that can run. A program might calculate a total, process a booking, or generate a report. The computer follows the rules you wrote; it does not work out what you meant.
Think about a study planner. Its information could be the time you planned and the time you already completed. Its rule could be to subtract completed time from planned time. Its result could be a message showing how much is left. That information → rule → result pattern is more important today than remembering a long list of keywords.
Java is also used to describe a wider platform of tools and libraries. The language gives you ways to express a program. The libraries provide ready-made operations, such as printing text or working with files. You learn both gradually, rather than rebuilding every operation yourself.
Where does Java fit in an application?
Java can be used for server applications, command-line utilities, desktop software, and other systems. In this course, we start with command-line programs because the inputs and results are visible without first learning a web framework or designing a user interface.
Imagine a website that accepts a reservation. The browser shows the form; a server checks the request and applies booking rules; a database stores the result. Java could implement that server logic. It would not replace HTML for document structure or SQL for querying the database. Different tools can handle different responsibilities in the same product.
Our first program is deliberately much smaller than a booking service. It has no database, network, account system, or graphical interface. Learning to describe its behavior accurately is a useful first step toward building those larger systems later.
Java and JavaScript are different languages
The names look related, but Java and JavaScript are not interchangeable names for one language. They have different language rules, libraries, and usual execution environments. Experience with one can help you recognize general ideas in the other, but it does not make their code interchangeable.
For example, JavaScript commonly prints with console.log, while our Java examples use System.out.println. A browser's JavaScript console cannot simply execute the Java class shown below. For local Java work, use a JDK and the Java commands introduced in this lesson.
You do not need to complete JavaScript before starting Java. Begin here if Java is your first language. If you know JavaScript already, pay attention to declared types and the explicit program structure instead of assuming similar-looking expressions behave identically.
The JDK, the JVM, and your editor have different jobs
Your editor is where you write and change text. It may offer syntax highlighting and a Run button, but the editor itself is not the Java language. Its Run button usually invokes other tools with settings you should eventually understand.
The JDK, or Java Development Kit, supplies development tools. Two names matter first: javac compiles Java source, and java launches a Java application. Installing only an editor does not guarantee either command is available in your terminal.
The JVM, or Java Virtual Machine, executes compiled class-file instructions. The JDK includes what you need to develop and run the examples here; you do not need to hunt for a separate JRE installation for this course. If you encounter the term JRE, think of the runtime environment rather than a source-code editor or compiler.
How a source file becomes a running program
We use an explicit two-step workflow: compile Main.java with javac, then launch Main with java. Compilation produces Main.class for this example. That class file contains bytecode, not a photograph of your source and not a document you need to edit by hand.
The JVM implementation on your machine executes the bytecode. It may interpret instructions and compile frequently used code to native instructions while running. You do not need those implementation details to write your first program, but they explain why saying Java is only interpreted or only compiled is incomplete.
A compatible JVM can run compatible bytecode on different operating systems. That is useful portability, not a promise that every Java application runs everywhere unchanged. Required Java versions, native libraries, file paths, and operating-system assumptions still matter. This course avoids preview features and uses a Java 21 language baseline.
You may see source-file launch commands such as java Main.java in other tutorials. They are another supported workflow. We separate compilation and launch here so you can see what each tool does. When you edit Main.java, compile it again before using java Main; otherwise you can accidentally run an older class file.
- Write
Main.javaSource you edit - Compile
javac Main.javaProduces Main.class - Launch
java MainThe JVM runs the program
Read your first program before changing it
Here is a small complete program. Its only job is to print two messages. Read the messages first and predict their order. Then use the explanation below to connect the visible result to the source.
Main.java · A two-line study message
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
My first Java study session
Today I will read, predict, and practise.public class Main- This declares a class named Main. For now, treat it as the named container around our program. Because this top-level class is public, save this example in Main.java with matching capitalization. Objects and class design come later.
{ and }- Matching braces group statements into a body. The outer pair surrounds the class; the inner pair surrounds the main method. Indentation helps you see these groups, but indentation does not replace braces.
public static void main(String[] args)- This is the conventional entry point used by these examples. public makes the method accessible; static lets it be called without first creating a Main object; void means it returns no value. String[] args can hold command-line arguments. We do not use those arguments yet.
System.out.println("My first Java study session");- This asks the standard output stream to print the text inside double quotes and finish the line. The quotes delimit a String value; they are not printed. The semicolon ends this statement.
Two println statements- These statements execute in order, producing two lines. Java does not display source-code lines just because they exist. The visible result comes from the printing operations that actually run.
You do not need to design your own use of static or arrays today. Keep the entry-point line intact while changing the messages inside it. Recognizing a structure is a reasonable first step; understanding every design choice comes through later lessons.
Optional: run it locally
If your JDK is already configured, save the example as Main.java in a new practice folder. Open a terminal in that folder and run the two commands below, one after the other. Continue only when compilation succeeds.
javac Main.java
java MainThe launch command is java Main, not java Main.class. Compare the two output lines with the expected output above. If the tools are unavailable, you can finish this lesson by reasoning through the examples and continue to the setup lesson for installation and verification.
Follow a small study planner from information to result
Now give the program a small calculation. You planned forty minutes and completed fifteen, so you expect twenty-five minutes left. Work out that answer yourself before reading the code. An independently calculated answer gives you something meaningful to check.
Main.java · Study-time planner
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Study plan
Minutes left: 25The first two lines inside main create named integer values. The third line subtracts the completed amount from the planned amount and stores the result. A variable is a name associated with a value; here the declared type int tells Java these are whole-number values.
The number 25 is not written into the final message. Java calculates it from the other values. In the last statement, the plus sign joins a text label and the calculated number into one message. Change completedMinutes to 20, save, compile, and run again: the number in the output should become 20.
For this first version, the information is written directly in the source. Nobody types a number while the program is running. It is not a timer and does not measure elapsed time. Describing those boundaries matters: a useful explanation says what the program actually implements, not what its name suggests.
Text is not the same as a calculation
Compare text with arithmetic
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
2 + 3
5Quotes make the first argument text, so Java prints the characters as written. Without quotes, the second argument is an arithmetic expression evaluated before printing. When output surprises you, ask whether you supplied text, a value, or an expression.
Predict, explain, then repair
Before changing the planner, write down the result for each case. Use planned minus completed, and explain the invalid case rather than treating a negative workload as a feature.
- 40 planned, 0 completed: how much remains?
- 40 planned, 40 completed: what boundary have you reached?
- 40 planned, 50 completed: what assumption has been broken?
Check your predictions
The results are 40, 0, and -10. The first two are valid under our assumption. The third shows that the program calculates without checking whether completed exceeds planned. A future improvement could reject invalid values; this version does not.
Repair a program that compiles but has the wrong rule
The next example contains a logic error. It still has valid Java syntax. Find the incorrect expression and describe the intended rule before revealing the repair.
Main.java · Find the incorrect calculation
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Reveal the repair and reasoning
Replace completedMinutes - plannedMinutes with plannedMinutes - completedMinutes. The broken version prints -25; the repaired version prints 25 for the given values. The compiler cannot know which subtraction matches your study-planning rule.
Independent lab: a session-planning report
Create a new Main.java that describes a study goal and reports remaining sessions. Work from these requirements first; reveal the example solution only after making your own attempt. If you are not running Java yet, write the intended output and explain the calculation on paper.
- Store the goal as text: Understand how Java runs.
- Use named values for six planned sessions and two completed sessions.
- Calculate remaining sessions instead of putting the answer directly in the output.
- Print the goal and the number of sessions left on separate labelled lines.
- Change completed to six and predict the new result.
- Explain what happens for seven completed sessions and which validation rule is missing.
Need a hint?
Keep the outer class and main structure from the earlier example. Use String for the goal and int for session counts. The calculation is planned minus completed. Printing a label plus a value follows the same pattern as the minutes report.
Reveal the explained solution
Main.java · Session planner solution
Predict the result, edit Main.java, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Goal: Understand how Java runs
Sessions left: 4The goal is a String because it is text. The three counts use int because sessions are whole units in this model. Keeping the calculation in remainingSessions gives the result a name and makes the output statement easier to read.
With six completed sessions, the final line becomes Sessions left: 0. With seven it becomes Sessions left: -1, exposing the same unhandled invalid state as the minutes example. No interactive input or validation has been added by this solution.
Review your own work
- Can you explain every output line without running the code?
- Is the result calculated from named inputs rather than typed as a fixed answer?
- Did you check the normal case and the zero-remaining boundary?
- Can you describe one limitation without claiming the program handles it?
Common mistakes and a useful debugging routine
Read the first useful message, classify the problem, and change one thing at a time. A missing tool, a compiler diagnostic, and an incorrect result require different kinds of investigation.
The terminal cannot find java or javac
This is a tool-installation or PATH problem, not proof that your program is wrong. Check java -version and javac -version. The next lesson covers setup; do not change source code to solve a missing compiler.
A public class and its filename do not match
For this example, public class Main belongs in Main.java, not main.java or StudyPlan.java. Keep the class name, filename, and launch command consistent. Java identifiers are case-sensitive.
The compiler points at a semicolon or quote error
Inspect the first diagnostic and the line before it. A missing closing quote or brace can make later lines appear wrong. Fix one cause, compile again, and read the new result rather than editing every highlighted line at once.
The program runs but prints the wrong number
Successful compilation checks language rules; it does not verify your intended calculation. Subtracting in the wrong direction can be legal Java. Compare actual output with a result you calculated independently.
The output did not change after editing
Save Main.java and compile again before launching Main. Check that your terminal is in the folder containing the file. Running a stale Main.class can make a correct edit look ineffective.
Questions beginners ask
Do I need to install Java before reading this lesson?
No. Read the examples, predict the output, and use Run code in the configured local preview. To run the same files yourself from a terminal, install a working JDK. Setup is the next lesson, not a prerequisite for understanding this introduction.
Do I need to understand object-oriented programming now?
No. Recognize the class and main method as the structure around the example. We will introduce objects when they solve a problem you have already seen. You should be able to explain the output before trying to design a class hierarchy.
Can I run these examples on this page?
Yes. Edit Main.java and select Run code in the local preview. The site compiles and runs your program in an isolated Java 21 container and displays actual output or diagnostics. It is not a browser interpreter. Source is sent only when you select Run; do not enter secrets. Public production execution requires separate infrastructure and is not enabled by this local runner.
Does Java automatically make a program correct or secure?
No. Language checks can catch some mistakes, but they cannot decide whether a study plan, booking rule, or access policy matches your intention. You still need validation, tests, and careful handling of failures.
What to take into the next lesson
A Java program is a precise description of behavior. The editor changes the source; javac compiles it; java launches the class using a JVM. In a small program, named information and a simple calculation already let you solve a recognizable problem.
Your most important habit is to predict a result, compare it with what the program does, and explain any difference. Syntax is necessary, but correct syntax is not the same as a correct rule. Next, we will prepare the JDK and editor so that this workflow is reproducible on your machine.
Related learning: Java course roadmap · Git and GitHub course. Continue to JDK and editor setup when you are ready.
Can you explain what runs?
Answer all six questions to check your understanding. Explanations appear after submission. Answers are temporary on this page, not saved course progress.
References and further reading
This lesson uses an original scenario, explanations, exercises, and quiz. W3Schools and GeeksforGeeks were consulted for introductory topic coverage. Technical details were checked against official Java documentation.
- W3Schools — Java Introduction — An alternative beginner overview; used as a topic-coverage reference, not a source of lesson wording or exercises.
- GeeksforGeeks — Introduction to Java — Another introductory perspective; the study-planner scenario and teaching sequence here are original.
- Dev.java — Your first Java code — Official guidance on writing and running your first Java program.
- Java Virtual Machine Specification, Java SE 21 — Introduction — The authoritative background for the JVM and compiled class-file model; optional deeper reading.
Last updated: