Java Basics: A Beginner's Guide

Java Basics: A Beginner's Guide

github.com/kristofer june 2025, v2

What is Java?

Java is a popular, object-oriented programming language designed to be platform-independent (“Write Once, Run Anywhere”). It’s used for desktop, web, mobile, and enterprise applications.

Basic Program Structure

Every Java program follows a specific structure that might seem complex at first, but serves important purposes. Unlike some languages where you can write code directly, Java requires all code to be inside classes, and every application needs a main method as its entry point. The public class declaration creates a blueprint for objects, static means the method belongs to the class itself rather than to any specific object, and void means the method doesn’t return a value. The String[] args parameter allows your program to receive command-line arguments.

While this structure might seem verbose compared to languages like Python, it provides benefits like better organization, type safety, and explicit program entry points that become valuable as programs grow larger and more complex.

1// HelloWorld.java
2public class HelloWorld {
3    public static void main(String[] args) {
4        System.out.println("Hello, World!");
5    }
6}

And this is why Java isn’t a beginner’s programming language.

Data Types

Data types are fundamental in programming because they define what kind of data a variable can hold and what operations can be performed on it. For example, numbers can be added or multiplied, while strings can be concatenated. Data types help the programmer (and the computer) understand how to store, process, and validate information, reducing errors and making code more predictable and efficient. Using the correct data type ensures your program behaves as expected and is easier to read and maintain.

Primitive Types

 1// Numbers
 2byte b = 127;            // 8-bit integer
 3short s = 32767;         // 16-bit integer
 4int i = 2147483647;      // 32-bit integer
 5long l = 9223372036854775807L;  // 64-bit integer
 6float f = 3.14f;         // 32-bit floating-point
 7double d = 3.14159;      // 64-bit floating-point
 8
 9// Other primitives
10char c = 'A';            // 16-bit Unicode character
11boolean bool = true;     // true or false

Reference Types

Reference types in Java represent objects rather than simple values. Unlike primitive types, which store actual data (like numbers or characters), reference types store a reference (or address) to an object in memory. This includes classes, arrays, interfaces, and strings. Reference types are central to Java because Java is an object-oriented language—most of the powerful features in Java, such as inheritance, polymorphism, and encapsulation, rely on objects. By using reference types, you can create complex data structures, reuse code, and model real-world entities more naturally. Understanding reference types is essential for working with Java’s standard libraries and building robust, maintainable applications.

1String str = "Hello";    // String literal
2Integer num = 42;        // Integer wrapper class
3Double pi = 3.14159;     // Double wrapper class

Variables and Constants

Variables in Java are strongly typed, meaning you must declare what type of data they will hold before using them. This might seem restrictive compared to dynamically typed languages, but it helps catch errors early and makes your code more predictable. Java separates variable declaration (telling the compiler what type of variable you want) from assignment (giving it a value), though you can do both at once for convenience.

Constants in Java use the final keyword, which truly prevents the value from being changed after initialization. This is different from conventions used in some other languages - Java enforces immutability at the compiler level. Constants are typically written in ALL_CAPS by convention and are often combined with static to make them shared across all instances of a class.

1// Variable declaration
2int number;              // Declaration
3number = 42;             // Assignment
4int value = 100;         // Declaration and assignment
5
6// Constants
7final double PI = 3.14159;  // Cannot be changed

Control Structures

Control structures in Java work similarly to other programming languages but require some specific syntax. Java uses curly braces {} to define code blocks, and conditions must be boolean expressions (evaluating to true or false). This strict typing helps prevent common programming errors where non-boolean values might be accidentally used in conditions.

Conditionals

Java’s conditional statements allow your program to make decisions based on different conditions. The if-else if-else chain lets you test multiple conditions in sequence, while the switch statement provides a clean way to handle multiple possible values of a single variable. Note that in traditional switch statements, you need break statements to prevent “fall-through” behavior where execution continues into the next case.

 1// If statement
 2if (condition) {
 3    // code
 4} else if (otherCondition) {
 5    // code
 6} else {
 7    // code
 8}
 9
10// Switch statement
11switch (value) {
12    case 1:
13        // code
14        break;
15    case 2:
16        // code
17        break;
18    default:
19        // code
20}

Loops

Java provides several types of loops for different situations. The traditional for loop gives you complete control over initialization, condition checking, and increment/decrement operations. The while loop continues as long as a condition is true, making it ideal when you don’t know in advance how many iterations you’ll need. The do-while loop guarantees at least one execution of the loop body. The enhanced for loop (for-each) provides a clean way to iterate through collections and arrays without dealing with index management.

 1// For loop
 2for (int i = 0; i < 5; i++) {
 3    // code
 4}
 5
 6// While loop
 7while (condition) {
 8    // code
 9}
10
11// Do-while loop
12do {
13    // code
14} while (condition);
15
16// For-each loop
17for (String item : collection) {
18    // code
19}

Arrays and Collections

Java distinguishes between arrays (fixed-size, low-level data structures) and collections (dynamic, feature-rich data structures). This separation gives you choice between performance and convenience. Arrays are faster and use less memory, while collections provide more functionality and flexibility.

Arrays

Arrays in Java are objects that store multiple values of the same type in a fixed-size sequential collection. Once you create an array, its size cannot be changed. Arrays provide fast access to elements by index and are memory-efficient, making them ideal when you know the exact number of elements you need. All array elements are initialized to default values (0 for numbers, null for objects, false for booleans) when the array is created.

1// Array declaration and initialization
2int[] numbers = new int[5];
3int[] values = {1, 2, 3, 4, 5};
4
5// Accessing elements
6numbers[0] = 42;
7int firstValue = values[0];

Collections

The Java Collections Framework provides dynamic data structures that can grow and shrink as needed. Unlike arrays, collections can change size during runtime and provide rich functionality through built-in methods. ArrayList is like a resizable array that automatically manages its size, while HashMap provides key-value mapping for fast lookups. Collections use generics (the <Type> syntax) to ensure type safety and avoid the need for casting.

 1// ArrayList
 2ArrayList<String> list = new ArrayList<>();
 3list.add("Hello");
 4list.remove(0);
 5list.size();
 6
 7// HashMap
 8HashMap<String, Integer> map = new HashMap<>();
 9map.put("key", 42);
10map.get("key");

Methods

Methods in Java are functions that belong to classes. They encapsulate reusable pieces of code and can accept parameters, perform operations, and return results. The method signature (name and parameters) must be unique within a class, but Java supports method overloading - having multiple methods with the same name but different parameter types or counts. This allows you to create flexible APIs that can handle different types of input.

Methods can be static (belonging to the class itself) or instance methods (belonging to specific objects). The access modifiers (public, private, protected) control who can call the method, supporting encapsulation principles.

1// Method declaration
2public static int add(int a, int b) {
3    return a + b;
4}
5
6// Method overloading
7public static double add(double a, double b) {
8    return a + b;
9}

Classes and Objects

Classes are the foundation of Java programming. A class serves as a blueprint that defines what data (fields) and behaviors (methods) objects will have. Java’s object-oriented approach means that almost everything is an object created from a class. Fields are typically private to maintain encapsulation - the principle that objects should control access to their internal data. Constructor methods have the same name as the class and are used to initialize new objects with appropriate starting values.

Access modifiers (private, public, protected) control visibility and help maintain proper encapsulation by hiding internal implementation details while exposing only the necessary interface.

Basic Class Structure

 1public class Person {
 2    // Fields (attributes)
 3    private String name;
 4    private int age;
 5    
 6    // Constructor
 7    public Person(String name, int age) {
 8        this.name = name;
 9        this.age = age;
10    }
11    
12    // Methods
13    public String getName() {
14        return name;
15    }
16    
17    public void setName(String name) {
18        this.name = name;
19    }
20}

Creating Objects

1Person person = new Person("John", 25);
2String name = person.getName();

Exception Handling

Exception handling in Java provides a structured way to deal with runtime errors. Java distinguishes between checked exceptions (which must be handled or declared) and unchecked exceptions (which can occur at runtime). The try-catch-finally structure allows you to attempt risky operations, handle specific types of errors appropriately, and ensure cleanup code always runs.

This approach makes Java programs more robust by forcing programmers to consider what might go wrong and handle errors gracefully rather than letting programs crash unexpectedly.

 1try {
 2    // Code that might throw an exception
 3    int result = 10 / 0;
 4} catch (ArithmeticException e) {
 5    // Handle the exception
 6    System.out.println("Cannot divide by zero!");
 7} finally {
 8    // Always executed
 9    System.out.println("Cleanup code");
10}

Input and Output

Java’s input and output operations require importing additional classes and creating objects to handle the operations. The Scanner class provides convenient methods for reading different types of input from the console, while System.out provides methods for displaying output. Unlike some languages where I/O is built into the basic syntax, Java’s approach provides more control and flexibility but requires more setup code.

Remember to import java.util.Scanner at the top of your file when using Scanner for input operations.

1// Console input
2Scanner scanner = new Scanner(System.in);
3String input = scanner.nextLine();
4int number = scanner.nextInt();
5
6// Console output
7System.out.println("Hello");  // With newline
8System.out.print("Hello");    // Without newline

Best Practices

  1. Follow Java naming conventions
    • Classes: PascalCase (MyClass)
    • Methods/Variables: camelCase (myMethod)
  2. Comment your code appropriately
  3. Handle exceptions properly
  4. Use meaningful variable and method names
  5. Keep methods small and focused
  6. Initialize variables before use
  7. Close resources (files, connections) properly

Next Steps

  1. Learn about inheritance and polymorphism
  2. Explore Java collections framework
  3. Study file I/O operations
  4. Learn about threads and concurrency
  5. Practice with small projects
  6. Explore Java frameworks (Spring, Hibernate)

Remember: Java is strongly typed and requires explicit type declarations. Start with simple programs and gradually move to more complex concepts.