0
0
Javaprogramming~15 mins

Writing first Java program - Deep Dive

Choose your learning style9 modes available
Overview - Writing first Java program
What is it?
Writing your first Java program means creating a simple set of instructions that a computer can follow using the Java language. Java programs are made of classes and methods that tell the computer what to do step by step. The first program usually prints a message on the screen to show everything is working. This is the starting point to learn how to tell computers what to do using Java.
Why it matters
This exists because computers need clear instructions to perform tasks, and Java is a popular language that helps people write those instructions in a way computers understand. Without learning to write a first program, you can't start building apps, games, or websites with Java. It’s like learning to write your name before writing a story. Without this step, you miss the foundation of programming and can’t create anything useful.
Where it fits
Before this, you should know what programming is and have a basic idea of how computers work. After learning to write your first Java program, you will learn about variables, data types, and how to control the flow of your program with decisions and loops.
Mental Model
Core Idea
A Java program is a set of instructions inside a class that the computer runs to perform tasks, starting with a special method called main.
Think of it like...
Writing your first Java program is like writing a recipe for a simple dish: you list the steps clearly so anyone (or any computer) can follow and get the same result.
┌─────────────────────────────┐
│         Java Program        │
│ ┌───────────────┐           │
│ │   Class       │           │
│ │ ┌───────────┐ │           │
│ │ │ main()    │ │           │
│ │ │ method    │ │           │
│ │ │ - steps   │ │           │
│ │ └───────────┘ │           │
│ └───────────────┘           │
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Java program structure
🤔
Concept: Java programs are organized into classes, and the main method is where the program starts running.
In Java, every program must have at least one class. Inside this class, there is a special method called main. The main method is the entry point where the computer begins executing your instructions. The basic structure looks like this: public class MyFirstProgram { public static void main(String[] args) { // instructions go here } }
Result
You have a skeleton of a Java program that the computer can run, even if it does nothing yet.
Knowing that Java programs start with a class and a main method helps you understand where to put your instructions and how the program runs.
2
FoundationPrinting output to the screen
🤔
Concept: Java uses System.out.println to show messages on the screen.
To see something happen, you can tell Java to print text on the screen. This is done with System.out.println("message"); inside the main method. For example: public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello, world!"); } }
Result
When run, the program shows the message: Hello, world!
Printing output is the simplest way to check your program works and to communicate with the user.
3
IntermediateCompiling and running Java programs
🤔Before reading on: Do you think Java code runs directly like a script, or does it need a step before running? Commit to your answer.
Concept: Java source code must be compiled into bytecode before the computer can run it.
Java code is written in files ending with .java. Before running, you must compile it using the Java compiler (javac). This turns your code into bytecode (.class files) that the Java Virtual Machine (JVM) can run. For example, to compile: javac MyFirstProgram.java To run the program: java MyFirstProgram This two-step process helps Java work on many types of computers.
Result
The program prints the message after compiling and running.
Understanding compilation explains why you need two commands and how Java stays portable across devices.
4
IntermediateExploring the main method signature
🤔Before reading on: Do you think the main method can have any name or parameters? Commit to your answer.
Concept: The main method must have a specific name and parameters for Java to recognize it as the program's starting point.
The main method looks like this: public static void main(String[] args) { // code } - public: means it can be called from anywhere. - static: means it belongs to the class, not an object. - void: means it returns nothing. - String[] args: an array of text inputs from the user. This exact signature is required for Java to start your program here.
Result
Java knows where to begin running your program.
Knowing the main method's exact form prevents errors and helps you understand how Java starts programs.
5
AdvancedUnderstanding Java class and file naming rules
🤔Before reading on: Do you think you can name your Java file anything regardless of the class name inside? Commit to your answer.
Concept: In Java, the public class name must match the filename exactly, including case.
If your class is named MyFirstProgram and is public, the file must be named MyFirstProgram.java. If they don't match, the compiler will give an error. This rule helps Java find and organize code correctly. For example: // File: MyFirstProgram.java public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello!"); } }
Result
Your program compiles and runs without naming errors.
Understanding this naming rule avoids frustrating compile errors and keeps your code organized.
6
ExpertHow JVM runs your first Java program internally
🤔Before reading on: Do you think the JVM runs your Java code directly or uses an intermediate step? Commit to your answer.
Concept: The JVM loads compiled bytecode, verifies it, and executes it using a stack-based engine, starting at the main method.
When you run java MyFirstProgram, the JVM: 1. Loads the MyFirstProgram.class bytecode. 2. Verifies the code is safe and correct. 3. Looks for the main method as the entry point. 4. Uses a stack to manage method calls and variables. 5. Executes instructions step by step. This process allows Java to run on any device with a JVM, making it platform-independent.
Result
Your program runs the instructions and shows output on the screen.
Knowing the JVM's role explains Java's portability and why compilation is separate from running.
Under the Hood
Java source code is first compiled by javac into bytecode, a platform-independent set of instructions stored in .class files. The Java Virtual Machine (JVM) then loads this bytecode, verifies its safety, and executes it using a stack-based interpreter or just-in-time compiler. The JVM starts execution at the main method, managing memory and method calls internally. This layered approach separates writing code from running it, enabling Java's 'write once, run anywhere' philosophy.
Why designed this way?
Java was designed in the 1990s to be portable across many devices, from computers to embedded systems. Compiling to bytecode instead of machine code allows the same program to run on any device with a JVM. This design trades off some speed for flexibility and security. Alternatives like compiling directly to machine code would limit portability and increase complexity.
┌───────────────┐      ┌───────────────┐      ┌───────────────┐
│ Java Source   │ ---> │ Java Compiler │ ---> │ Bytecode (.class)│
│ (.java file)  │      │ (javac)       │      │               │
└───────────────┘      └───────────────┘      └───────────────┘
                                               │
                                               ▼
                                      ┌─────────────────┐
                                      │ Java Virtual    │
                                      │ Machine (JVM)   │
                                      └─────────────────┘
                                               │
                                               ▼
                                      ┌─────────────────┐
                                      │ Program Runs    │
                                      │ (main method)   │
                                      └─────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does Java run your .java file directly without compiling? Commit to yes or no.
Common Belief:Java code runs directly like a script without needing compilation.
Tap to reveal reality
Reality:Java source code must be compiled into bytecode before running; the JVM runs the bytecode, not the source file.
Why it matters:Trying to run .java files directly causes errors and confusion about how Java programs execute.
Quick: Can the main method have any name and still be the program's start? Commit to yes or no.
Common Belief:You can name the main method anything you want; Java will find it automatically.
Tap to reveal reality
Reality:The main method must be named exactly 'main' with the correct signature for Java to recognize it as the entry point.
Why it matters:Incorrect main method names cause the program not to run, leading to frustrating errors for beginners.
Quick: Does the Java filename have to match the public class name inside? Commit to yes or no.
Common Belief:You can name your Java file anything regardless of the class name inside.
Tap to reveal reality
Reality:If a class is public, the filename must exactly match the class name, including case.
Why it matters:Mismatched names cause compile-time errors, blocking program execution.
Quick: Does the JVM execute Java source code directly? Commit to yes or no.
Common Belief:The JVM runs Java source code directly without any intermediate steps.
Tap to reveal reality
Reality:The JVM runs compiled bytecode, not source code, ensuring platform independence and security.
Why it matters:Misunderstanding this leads to confusion about Java's portability and runtime behavior.
Expert Zone
1
The main method's String[] args parameter allows passing command-line arguments, enabling flexible program input without changing code.
2
Java's strict class and file naming conventions support the JVM's class loader mechanism, which dynamically loads classes at runtime.
3
The JVM uses a stack-based execution model, which differs from register-based machines, affecting performance and debugging.
When NOT to use
Writing a first Java program is not suitable when you need quick scripts or small programs without setup; languages like Python or JavaScript are better for rapid prototyping. Also, for system-level programming or very high-performance needs, languages like C or Rust are preferred.
Production Patterns
In real-world Java projects, the first program evolves into multiple classes organized in packages, using build tools like Maven or Gradle to compile and run. The main method often delegates to other classes, and output is managed with logging frameworks instead of simple print statements.
Connections
Python scripting
Alternative approach for beginners to write and run code quickly without compilation.
Understanding Java's compile-run cycle highlights why scripting languages like Python can be faster to start but less portable.
Operating system boot process
Both have a defined entry point where execution begins (main method in Java, bootloader in OS).
Recognizing entry points in different systems helps understand program and system startup sequences.
Recipe writing in cooking
Both involve clear, step-by-step instructions to achieve a result.
Seeing programming as writing recipes makes the concept of instructions and order intuitive.
Common Pitfalls
#1Trying to run Java source code directly without compiling.
Wrong approach:java MyFirstProgram.java
Correct approach:javac MyFirstProgram.java java MyFirstProgram
Root cause:Misunderstanding that Java requires compilation before running.
#2Naming the main method incorrectly or changing its signature.
Wrong approach:public static void Main(String args) { }
Correct approach:public static void main(String[] args) { }
Root cause:Not knowing Java's strict requirements for the main method signature.
#3Saving the Java file with a name different from the public class inside.
Wrong approach:// File: Program.java public class MyFirstProgram { ... }
Correct approach:// File: MyFirstProgram.java public class MyFirstProgram { ... }
Root cause:Ignoring Java's rule that public class names must match filenames exactly.
Key Takeaways
A Java program starts with a class containing a main method where execution begins.
You must compile Java source code into bytecode before running it with the JVM.
The main method must have the exact signature for Java to recognize it as the entry point.
Java requires the filename to match the public class name to compile successfully.
Understanding these basics sets the foundation for writing and running any Java program.