Skip to content

Java Basics — Complete Beginner's Guide

DodaTech Updated 2026-06-20 10 min read

In this tutorial, you'll learn about Java Basics. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Java is a statically-typed, object-oriented language that runs on billions of devices via the JVM, making it the standard for enterprise backends and Android apps.

What You'll Learn

You'll understand how to set up Java, write your first program, use variables and data types, control program flow with conditionals and loops, work with arrays, and handle basic input and output. By the end, you'll be ready for the Java OOP tutorial.

Why Java Matters

Java powers over 3 billion devices worldwide. It's the backbone of Android apps, enterprise servers, financial trading systems, and big data infrastructure. DodaTech's Durga Antivirus Pro uses Java for its cross-platform desktop client — the ability to write once and run anywhere allows us to deploy the same codebase on Windows, macOS, and Linux without changes.

Real-World Use: A Configuration Loader

Imagine building a tool that reads device configuration files in a security dashboard. You need to parse settings, validate IP addresses, and flag anomalies. Java's strong typing catches type mismatches at compile time — before they reach production. This is the same pattern used in DodaTech's network monitoring tools.

Java Learning Path

flowchart LR
  A[No Programming Experience] --> B[Java Basics]
  B --> C[Java OOP]
  C --> D[Java Collections]
  C --> E[Java Exceptions]
  D --> F[Java Streams & Lambdas]
  D --> G[Java Concurrency]
  B:::current

  classDef current fill:#3b82f6,color:#fff,stroke:#333,stroke-width:2px

Setting Up Java

Before writing code, you need the Java Development Kit (JDK). Java 21 is the latest LTS release as of 2026, and it's what we'll use throughout this tutorial.

# Check if Java is installed
java -version

# Expected output (version may vary):
# openjdk version "21.0.3" 2026-04-15 LTS
# OpenJDK Runtime Environment (build 21.0.3+9)
# OpenJDK 64-Bit Server VM (build 21.0.3+9, mixed mode)

If Java isn't installed, download it from oracle.com or use a package manager:

# Ubuntu/Debian
sudo apt install openjdk-21-jdk

# macOS (Homebrew)
brew install openjdk@21

Your First Java Program

Every Java program needs a class definition and a main method — this is the entry point where execution begins.

public class HelloDodaTech {
    public static void main(String[] args) {
        System.out.println("Hello from DodaTech!");
        System.out.println("Java version: " + System.getProperty("java.version"));
    }
}

Compile and run:

javac HelloDodaTech.java
java HelloDodaTech

Expected output:

Hello from DodaTech!
Java version: 21.0.3

The javac command compiles .java source files into .class bytecode. The java command launches the JVM and executes that bytecode. This two-step Process is what makes Java platform-independent — bytecode runs anywhere a JVM exists.

Variables and Data Types

Think of a variable as a labeled storage box. You put a value inside, and the label tells you what type of value it holds. Java requires you to declare the type upfront — this is called static typing.

public class VariablesDemo {
    public static void main(String[] args) {
        // Primitive types — store actual values
        int deviceCount = 42;
        double temperature = 36.5;
        boolean isConnected = true;
        char statusSymbol = 'A';
        long fileSize = 9223372036854775807L;  // 'L' suffix for long
        float signalStrength = -67.5f;          // 'f' suffix for float

        // Reference type — stores a memory address
        String deviceName = "Sensor-Gamma-7";

        System.out.println("Device: " + deviceName);
        System.out.println("Count: " + deviceCount);
        System.out.println("Connected: " + isConnected);
        System.out.println("Signal: " + signalStrength + " dBm");
    }
}

Expected output:

Device: Sensor-Gamma-7
Count: 42
Connected: true
Signal: -67.5 dBm

Key points for beginners:

  • int holds whole numbers (32-bit)
  • double holds decimal numbers (64-bit)
  • boolean holds true or false
  • char holds a single character (16-bit Unicode)
  • String is not a primitive — it's a class, but Java gives it special syntax with double quotes

Variable Naming Rules

Rule Example Why
Start with letter, $, or _ deviceName ✓, 1device Compiler needs to distinguish names from numbers
Use camelCase signalStrength Java convention — improves readability
No reserved keywords class ✗, int Keywords have special meaning in the language
Case-sensitive deviceDevice Java treats uppercase and lowercase as different

Operators

Operators are symbols that perform operations on values. Java categorizes them into several groups:

public class OperatorsDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 3;

        // Arithmetic
        System.out.println("Sum: " + (a + b));         // 13
        System.out.println("Difference: " + (a - b));   // 7
        System.out.println("Product: " + (a * b));      // 30
        System.out.println("Quotient: " + (a / b));     // 3 (integer division!)
        System.out.println("Remainder: " + (a % b));    // 1

        // Comparison — always return boolean
        System.out.println("Equal: " + (a == b));       // false
        System.out.println("Greater: " + (a > b));      // true

        // Logical
        boolean highTemp = true;
        boolean lowBattery = false;
        System.out.println("Alert: " + (highTemp && !lowBattery));  // true
    }
}

Expected output:

Sum: 13
Difference: 7
Product: 30
Quotient: 3
Remainder: 1
Equal: false
Greater: true
Alert: true

Watch out for integer division! 10 / 3 gives 3, not 3.33. Java truncates the decimal when both operands are integers. Use double if you need fractional results.

Control Flow

Control flow statements let your program make decisions and repeat actions. Think of them as traffic lights and roundabouts for your code.

If-Else — Making Decisions

public class IfElseDemo {
    public static void main(String[] args) {
        int signalLevel = -80;  // dBm

        if (signalLevel > -50) {
            System.out.println("Excellent signal");
        } else if (signalLevel > -70) {
            System.out.println("Good signal");
        } else if (signalLevel > -85) {
            System.out.println("Fair signal");
        } else {
            System.out.println("Poor signal — possible disconnection");
        }
    }
}

Expected output:

Fair signal

Loops — Repeating Actions

public class LoopsDemo {
    public static void main(String[] args) {
        String[] devices = {"Router", "Switch", "Firewall", "AP"};

        // For loop — use when you know the number of iterations
        for (int i = 0; i < devices.length; i++) {
            System.out.println("Device " + (i + 1) + ": " + devices[i]);
        }

        System.out.println("---");

        // For-each loop — cleaner when you don't need the index
        for (String device : devices) {
            System.out.println("Scanning: " + device);
        }
    }
}

Expected output:

Device 1: Router
Device 2: Switch
Device 3: Firewall
Device 4: AP
---
Scanning: Router
Scanning: Switch
Scanning: Firewall
Scanning: AP

Arrays

An array is a numbered list where every element has the same type. Think of it like a row of lockers — each one has a number and holds one item.

public class ArraysDemo {
    public static void main(String[] args) {
        // Declaration and initialization
        int[] ports = {22, 80, 443, 8080, 3306};

        // Access by index (0-based)
        System.out.println("SSH port: " + ports[0]);     // 22
        System.out.println("Web port: " + ports[2]);     // 443

        // Modify an element
        ports[3] = 8443;  // Change port 8080 to 8443
        System.out.println("Updated port: " + ports[3]); // 8443

        // Iterate with sum
        int total = 0;
        for (int port : ports) {
            total += port;
        }
        System.out.println("Sum of ports: " + total);
    }
}

Expected output:

SSH port: 22
Web port: 443
Updated port: 8443
Sum of ports: 8554

Arrays have a fixed size in Java. Once created with new int[5] or {...}, you cannot add or remove positions. Use Java Collections (like ArrayList) when you need a dynamic size.

What Is the Difference Between JDK, JRE, and JVM?

The JDK (Java Development Kit) includes the JRE (Java Runtime Environment), which includes the JVM (Java Virtual Machine). The JDK has compilers and debuggers for development. The JRE has libraries and the JVM for running programs. The JVM executes bytecode and provides memory management and security.

Common Mistakes Beginners Make

  1. Missing main method signature: public static void main(String[] args) must be exact. Missing static causes "Main method not found." Every Java application needs this exact entry point.

  2. Forgetting semicolons: Every statement must end with ;. Missing one gives a compilation error pointing to the next line, which can be confusing.

  3. Off-by-one errors in arrays: Array indices go from 0 to length - 1. Accessing array[array.length] throws ArrayIndexOutOfBoundsException.

  4. Integer division without realizing it: int result = 5 / 2; gives 2, not 2.5. Use 5 / 2.0 or cast to double.

  5. Comparing strings with ==: == checks reference equality (same object), not value equality. Always use string1.equals(string2) for content comparison.

  6. Uninitialized local variables: Local variables must be assigned a value before use. The compiler enforces this — you'll get a "variable might not have been initialized" error.

  7. Case sensitivity errors: system.out.println won't compile — it must be System.out.println. Java is case-sensitive, so Device and device are different identifiers.

Practice Questions

  1. What is the difference between int and double?
  2. Why does 10 / 4 equal 2 in Java?
  3. What is the output of System.out.println("Hello" + 5 + 3);?
  4. How do you declare an array of 10 integers?
  5. What happens if you access arr[arr.length] on an array?

Answers:

  1. int stores whole numbers (32-bit); double stores decimal numbers (64-bit) with higher precision.
  2. Because both operands are integers, Java performs integer division and truncates the fractional part. Use 10 / 4.0 for 2.5.
  3. "Hello53" — the + operator concatenates strings, converting numbers to strings along the way.
  4. int[] arr = new int[10]; or int[] arr = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  5. It throws ArrayIndexOutOfBoundsException because valid indices are 0 through length - 1.

Challenge

Write a program that takes an array of integers representing network port numbers and prints only the ports that are greater than 1024 (non-privileged ports). Use a for-each loop and an if condition. Extend it to also count how many privileged ports (≤ 1024) exist.

Real-World Task

Build a simple configuration parser that reads device names and IP addresses from a hardcoded array, validates that each IP has four octets, and prints a security report showing which devices have valid vs invalid IPs. This mirrors the pattern DodaTech's network discovery tools use to inventory devices on a subnet.

FAQ

What is the difference between JDK, JRE, and JVM?

: The JDK (Java Development Kit) includes compilers and tools for developing Java programs. The JRE (Java Runtime Environment) includes libraries and the JVM for running Java programs. The JVM (Java Virtual Machine) executes compiled bytecode and provides memory management. You need the JDK to write Java code, but only the JRE to run it.

Why is Java called "platform-independent"?

: Java source code compiles to bytecode (.class files), which runs on the JVM. Each platform has its own JVM implementation, but the bytecode is the same everywhere. This "write once, run anywhere" philosophy is what makes Java platform-independent.

What does `public static void main(String[] args)` mean?

: public makes the method accessible to the JVM. static allows it to run without creating an object. void means it returns nothing. main is the method name the JVM looks for. String[] args holds command-line arguments passed to the program.

What's Next

Java OOP — Object-Oriented Programming Explained
Java Exception Handling Guide
Java Collections Framework
Java Streams Guide

Related topics: Java, Java OOP, JVM, Java Collections, Maven

Remember: every expert was once a beginner. Start with one program, then build something every day. Consistency matters more than hours.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro