Your First Java Program
Hello World and program structure
The Hello, World! Program
The quintessential first program in any programming language is often "Hello, World!". This simple program serves as a gentle introduction to the syntax and structure of the language, and it's a great way to ensure your setup is working properly.
Here's what the code looks like:
Let's break this down:
public class HelloWorld: This is declaring a class named HelloWorld. In Java, everything resides within classes.public static void main(String[] args): This is the main method where program execution begins. It must be exactly as specified, or the Java Virtual Machine (JVM) won't recognize it.System.out.println("Hello, World!");: This line prints the text "Hello, World!" to the console. It's a method call that outputs the string, followed by a newline.
Running Your Program
To run this program, you'll need to:
- Save the code in a file named
HelloWorld.java. - Open your terminal or command prompt and navigate to the directory where you saved the file.
- Compile the program using the command:
javac HelloWorld.java - This creates a
HelloWorld.classfile, which contains the bytecode that the JVM understands. - Now, run the program with:
java HelloWorld
You should see the output: Hello, World!
Understanding this process is crucial because it lays the groundwork for how Java programs are structured and executed.
Structure of a Java Program
Now that you've run your first program, let's delve deeper into the structure of a Java program. This is where you'll start to appreciate Java's object-oriented principles and syntax rules.
Basic Components
Every Java program has several key components:
- Classes: The building blocks of Java. Each Java application is made up of at least one class.
- Methods: Blocks of code that perform specific tasks. The main method we saw earlier is a special method.
- Variables: Used to store data values. You define them with a type and a name, such as
int number.
Why Structure Matters
Understanding the structure helps you in the following ways:
- It reinforces the concept of reusability. Methods can be called multiple times with different arguments.
- It encourages better organization of code, making it easier to debug and maintain.
Variables and Data Types
Next up, let's take a closer look at variables and data types. These are foundational concepts in any programming language, and Java is no exception.
Java Data Types
Java has two main categories of data types: primitive types and reference types.
Primitive Types
These include:
int: For integers.double: For decimal numbers.char: For single characters.boolean: For true/false values.
Reference Types
These include objects, strings, and arrays. For example, strings are widely used in Java.
Understanding Variable Scope
Variables have a scope, which determines where they can be accessed. For instance, a variable declared inside a method is local to that method and cannot be accessed outside of it.
ā ļø Common Gotcha: One common mistake is not initializing variables before use. Java requires that local variables be initialized before they are used.
Control Flow Statements
As you build more complex programs, you'll need to control the flow of execution. Java provides several control flow statements, including conditionals and loops.
Conditionals
Conditionals allow your program to make decisions. The if statement is the most common.
Loops
Loops allow you to execute a block of code multiple times. The for loop and while loop are widely used.
Best Practices
- Keep your loops simple. Complex conditions can lead to bugs.
- Always ensure your loops will terminate. Infinite loops can crash your program.
Error Handling Basics
As a developer, you will inevitably face errors, whether they are syntax errors, runtime exceptions, or logical errors. Java provides a robust way to handle errors through exceptions.
Try-Catch Block
You can use try-catch blocks to gracefully handle exceptions.
Why Handle Exceptions?
Proper error handling makes your program more robust and user-friendly. Instead of crashing, your program can provide meaningful feedback and continue operating in a controlled manner.
ā ļø Common Pitfall: Catching general exceptions without specifying the type can hide bugs and make debugging difficult. Always be as specific as possible with your exceptions.
Next Chapter: Now that you understand how to create and run Java programs, you are ready to explore how Java works under the hood. In the next chapter, we will look at the inner workings of the Java language, including the role of the Java Virtual Machine and how it executes your code efficiently.
Code Examples
The quintessential Hello World program. Save this as HelloWorld.java, compile with javac, and run with java.
1public class HelloWorld {
2 public static void main(String[] args) {
3 System.out.println("Hello, World!");
4 }
5}Commands to compile and run your first Java program. The output will be: Hello, World!
1# Compile the program
2javac HelloWorld.java
3
4# This creates a HelloWorld.class file
5
6# Run the program
7java HelloWorldA more complex program showing class structure, methods, and reusability. The main method calls the add method which returns the sum of two integers.
1public class Calculator {
2 public static void main(String[] args) {
3 int sum = add(5, 10);
4 System.out.println("The sum is: " + sum);
5 }
6
7 public static int add(int a, int b) {
8 return a + b;
9 }
10}Demonstrates different primitive data types in Java: int, double, char, and boolean.
1public class DataTypesExample {
2 public static void main(String[] args) {
3 int age = 25;
4 double height = 5.9;
5 char initial = 'J';
6 boolean isStudent = false;
7
8 System.out.println("Age: " + age);
9 System.out.println("Height: " + height);
10 System.out.println("Initial: " + initial);
11 System.out.println("Is Student: " + isStudent);
12 }
13}Example of a reference type - String. Strings are objects in Java, not primitive types.
1public class StringExample {
2 public static void main(String[] args) {
3 String greeting = "Hello, Java!";
4 System.out.println(greeting);
5 }
6}This code will NOT compile. Java requires local variables to be initialized before use. This is a common mistake for beginners.
1public class ErrorExample {
2 public static void main(String[] args) {
3 int value; // declared but not initialized
4 System.out.println(value); // error: variable value might not have been initialized
5 }
6}Demonstrates conditional statements (if-else). The program checks the score and prints the appropriate grade.
1public class ConditionalExample {
2 public static void main(String[] args) {
3 int score = 85;
4
5 if (score >= 90) {
6 System.out.println("Grade: A");
7 } else if (score >= 80) {
8 System.out.println("Grade: B");
9 } else {
10 System.out.println("Grade: C");
11 }
12 }
13}For loop example that iterates 5 times, printing the iteration number each time.
1public class LoopExample {
2 public static void main(String[] args) {
3 for (int i = 0; i < 5; i++) {
4 System.out.println("Iteration: " + i);
5 }
6 }
7}While loop example that executes as long as the condition (count < 5) is true.
1public class WhileLoopExample {
2 public static void main(String[] args) {
3 int count = 0;
4 while (count < 5) {
5 System.out.println("Count: " + count);
6 count++;
7 }
8 }
9}Exception handling with try-catch. Instead of crashing, the program catches the ArrayIndexOutOfBoundsException and prints a friendly message.
1public class ExceptionExample {
2 public static void main(String[] args) {
3 try {
4 int[] numbers = {1, 2, 3};
5 System.out.println(numbers[5]); // This will cause an ArrayIndexOutOfBoundsException
6 } catch (ArrayIndexOutOfBoundsException e) {
7 System.out.println("Array index is out of bounds!");
8 }
9 }
10}Use Cases
- Learning basic Java syntax, program structure, and compilation process
- Understanding class-based structure and the main method entry point
- Mastering primitive and reference data types for variable declarations
- Implementing control flow with conditionals and loops
- Practicing proper exception handling for robust applications
- Building foundational skills for creating reusable methods and organized code
Common Mistakes to Avoid
- File name not matching the public class name (Java is case-sensitive)
- Forgetting semicolons at the end of statements
- Missing curly braces or mismatched brackets
- Incorrect main method signature - must be exactly: public static void main(String[] args)
- Not initializing local variables before using them
- Creating infinite loops by forgetting to update the loop condition
- Catching generic Exception instead of specific exception types
- Using = (assignment) instead of == (comparison) in conditionals