CIPHERCODE.AI · JAVA BEGINNER

Java from zero

Install the JDK, write your first program and finish able to build small console apps.

  • 6 modules
  • Line-by-line code
  • Quizzes + practice

    Module 1

    JDK setup and your first program

    Understand JDK, JRE and JVM, install Java, then compile and run Hello World.

    About 45 minutes

    Java is a compiled, object-oriented language. You write source code in .java files, the compiler javac turns it into bytecode (.class files), and the JVM runs that bytecode. Because the JVM exists for Windows, macOS and Linux, the same compiled program runs everywhere. This idea is called "write once, run anywhere".

    PieceWhat it isWho needs it
    JVMRuns bytecode on your machineEveryone, it is inside the JDK
    JREJVM plus core librariesOnly to run programs
    JDKJRE plus javac and toolsYou, since you write code

    Install and verify

    Install a current LTS JDK (17 or 21) from adoptium.net or oracle.com. Open a terminal and check both the runner and the compiler.

    terminal
    java -version
    javac -version
    If javac is not found, the JDK bin folder is missing from PATH.

    Your first program

    Hello.java
    public class Hello {
        public static void main(String[] args) {
            System.out.println("Hello, CipherCode!");
        }
    }
    Line 1 declares a class named Hello. Line 2 is the entry point the JVM looks for. Line 3 prints text then a new line. Every statement ends with ; and blocks use { }.

    Key takeaways

    • Source .java -> javac -> bytecode .class -> JVM runs it
    • Install the JDK, not only the JRE
    • main is the entry point; statements end with ;
    • Class name and file name must match

    Practice

    Write Me.java that prints your name on one line and your city on the next.

    Use two System.out.println calls inside main. Class name must be Me.

    Me.java
    public class Me {
        public static void main(String[] args) {
            System.out.println("Asha");
            System.out.println("Vijayawada");
        }
    }

    Quick quiz

    Which tool turns Hello.java into bytecode?

    Module 2

    Variables, data types and input

    Store data with the right type, convert between types, and read keyboard input.

    About 60 minutes

    Java is statically typed: every variable has a type fixed at declaration. A variable is a named box; the type decides what fits inside.

    TypeHoldsExample
    intWhole numbers (about +-2 billion)int age = 21;
    longBigger whole numberslong pop = 1400000000L;
    doubleDecimalsdouble price = 19.99;
    booleantrue or falseboolean ok = true;
    charOne character, single quoteschar grade = 'A';
    StringText, double quotes (a class, not primitive)String name = "Ravi";
    Types.java
    public class Types {
        public static void main(String[] args) {
            int qty = 3;
            double price = 12.5;
            double total = qty * price;   // int widens to double
            int whole = (int) total;      // cast drops .5
            String msg = "Total: " + total;
            System.out.println(msg);
            System.out.println(whole);
            System.out.println(7 / 2);    // integer division
            System.out.println(7 % 2);    // remainder
        }
    }
    Line by line: qty * price mixes int and double so Java widens to double. (int) is a manual narrowing cast and truncates. 7 / 2 is 3 because both sides are int; % gives the remainder.

    Reading input

    Greet.java
    import java.util.Scanner;
    
    public class Greet {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            System.out.print("Name: ");
            String name = sc.nextLine();
            System.out.print("Age: ");
            int age = sc.nextInt();
            System.out.println(name + " will be " + (age + 1) + " next year");
            sc.close();
        }
    }
    import brings in Scanner. new Scanner(System.in) wraps the keyboard. nextLine() reads text, nextInt() reads a number. + between a String and a number joins them.

    Key takeaways

    • Types are fixed at declaration; pick the smallest fitting one
    • Widening is automatic; narrowing needs a cast
    • int / int stays an int
    • Scanner reads input: nextLine for text, nextInt for numbers

    Practice

    Read two numbers and print their average as a decimal.

    Read with nextDouble, or divide by 2.0.

    Avg.java
    import java.util.Scanner;
    public class Avg {
        public static void main(String[] a) {
            Scanner sc = new Scanner(System.in);
            double x = sc.nextDouble(), y = sc.nextDouble();
            System.out.println((x + y) / 2);
        }
    }

    Quick quiz

    What does System.out.println(10 / 4); print?

    Module 3

    Decisions and loops

    Make programs choose with if and switch, and repeat work with for, while and do-while.

    About 60 minutes

    Conditions use booleans. Comparisons are == != < > <= >=; combine them with && (and), || (or), ! (not). Never compare Strings with ==; use .equals().

    Control.java
    public class Control {
        public static void main(String[] args) {
            int marks = 72;
            if (marks >= 90) System.out.println("A");
            else if (marks >= 60) System.out.println("B");
            else System.out.println("C");
    
            int day = 3;
            switch (day) {
                case 1: System.out.println("Mon"); break;
                case 3: System.out.println("Wed"); break;
                default: System.out.println("Other");
            }
            for (int i = 1; i <= 3; i++) {
                System.out.println("Round " + i);
            }
            int n = 3;
            while (n > 0) { n--; }
            System.out.println(n);
        }
    }
    The if-chain stops at the first true branch (72 gives B). switch jumps to the matching case; break stops fall-through. The for has three parts: start i = 1, test i <= 3, step i++. while tests first, so it may run zero times.

    Key takeaways

    • if / else if / else picks one branch
    • Strings are compared with .equals()
    • switch needs break per case
    • for = counted, while = condition, do-while = at least once

    Practice

    Print the multiplication table of 5 from 1 to 10.

    A for loop with i from 1 to 10 and print 5 * i.

    Table.java
    public class Table {
        public static void main(String[] a) {
            for (int i = 1; i <= 10; i++)
                System.out.println("5 x " + i + " = " + 5 * i);
        }
    }

    Quick quiz

    Which compares two Strings correctly?

    Module 4

    Methods and arrays

    Package logic into reusable methods and store many values in an array.

    About 60 minutes

    A method is a named block of code with parameters and a return type. An array is a fixed-size, zero-indexed list of one type.

    Stats.java
    public class Stats {
        static int sum(int[] nums) {
            int total = 0;
            for (int n : nums) total += n;
            return total;
        }
        static double average(int[] nums) {
            return (double) sum(nums) / nums.length;
        }
        public static void main(String[] args) {
            int[] marks = {70, 85, 90};
            System.out.println(marks[0]);
            System.out.println(sum(marks));
            System.out.println(average(marks));
        }
    }
    static int sum(int[] nums): static so main can call it, int is the return type, int[] nums is the parameter. for (int n : nums) is the for-each loop. .length is the array size (no brackets). Indexes start at 0, so marks[0] is 70.

    Key takeaways

    • Method = return type + name + parameters
    • Arrays are zero-indexed with fixed size
    • for-each loops read every element
    • Overloading reuses a name with different parameters

    Practice

    Write a method max(int[] a) that returns the largest value.

    Start with best = a[0], then update inside a loop.

    Max.java
    static int max(int[] a) {
        int best = a[0];
        for (int n : a) if (n > best) best = n;
        return best;
    }

    Quick quiz

    Valid indexes for int[] a = new int[5]; are:

    Module 5

    Classes and objects

    Model real things with fields, constructors, methods and encapsulation.

    About 75 minutes

    A class is a blueprint; an object is one thing built from it with new. Fields hold data, methods hold behaviour, and the constructor sets up a new object. Mark fields private and expose them through methods: this is encapsulation.

    Account.java
    public class Account {
        private String owner;
        private double balance;
    
        public Account(String owner, double balance) {
            this.owner = owner;
            this.balance = balance;
        }
        public void deposit(double amt) {
            if (amt > 0) balance += amt;
        }
        public double getBalance() { return balance; }
    
        public static void main(String[] args) {
            Account a = new Account("Asha", 500);
            a.deposit(250);
            System.out.println(a.getBalance());
        }
    }
    this.owner = owner copies the parameter into the field (this = the current object). private stops outside code changing balance directly, so deposit can validate. new Account(...) calls the constructor and returns the object.

    Key takeaways

    • Class = blueprint, object = instance made with new
    • Constructor has the class name and no return type
    • this means the current object
    • Private fields + public methods = encapsulation

    Practice

    Create Student with name and marks, a constructor, and a method isPass() that returns true when marks >= 40.

    Return marks >= 40 directly, it is already a boolean.

    Student.java
    public class Student {
        private String name;
        private int marks;
        public Student(String name, int marks) { this.name = name; this.marks = marks; }
        public boolean isPass() { return marks >= 40; }
    }

    Quick quiz

    What does this.balance = balance; do?

    Module 6

    Collections and exceptions

    Use ArrayList and HashMap, and handle errors with try and catch.

    About 75 minutes

    ArrayList is a resizable list; HashMap stores key-value pairs. Angle brackets name the element type (generics) so the compiler catches wrong types.

    Shop.java
    import java.util.*;
    
    public class Shop {
        public static void main(String[] args) {
            List<String> items = new ArrayList<>();
            items.add("Pen");
            items.add("Book");
            System.out.println(items.size() + " " + items.get(1));
    
            Map<String, Integer> price = new HashMap<>();
            price.put("Pen", 10);
            price.put("Book", 120);
            System.out.println(price.get("Book"));
    
            try {
                int bad = Integer.parseInt("abc");
            } catch (NumberFormatException e) {
                System.out.println("Not a number");
            } finally {
                System.out.println("Done");
            }
        }
    }
    List<String> is declared as the interface and built as ArrayList (a good habit). add, get, size are the core calls. price.put(key, value) stores; price.get(key) reads. Code that might fail goes in try; the matching catch runs only on that error; finally always runs.

    Key takeaways

    • ArrayList grows; arrays do not
    • HashMap gives fast lookup by key
    • try / catch / finally handles runtime errors
    • Use generics: List<String>, Map<String, Integer>

    Practice

    Store 3 names in an ArrayList and print each using a for-each loop.

    for (String n : items) then print n.

    Names.java
    List<String> items = new ArrayList<>(List.of("A","B","C"));
    for (String n : items) System.out.println(n);

    Quick quiz

    Which always runs, error or not?

    EXAM READINESS EXTENSION · BEGINNER

    The extra fundamentals Java exams expect

    The six core lessons give you a strong start. Exams also test exact language rules, tracing output, short programs, and explanations of why code behaves a certain way. Use this extension as a revision sheet; examples use standard Java syntax and can be adapted to your syllabus.

    Definition bank: Core Java definitions

    Learn these concise definitions for theory questions. In written exams, define the term first, then add a short example when asked.

    Java
    A high-level, class-based programming language designed to run on different platforms through the Java Virtual Machine (JVM).
    JDK (Java Development Kit)
    The tools used to develop Java programs, including the compiler and runtime tools.
    JRE (Java Runtime Environment)
    The runtime components needed to run Java applications; in modern Java distributions, it is commonly delivered as part of a JDK or runtime image.
    JVM (Java Virtual Machine)
    The virtual machine that executes Java bytecode and manages runtime services such as memory.
    Source code
    Human-readable program text written in a language such as Java and saved in a .java file.
    Bytecode
    Platform-independent instructions produced by the Java compiler and usually stored in .class files.
    Compiler
    A program that translates Java source code into bytecode; the Java compiler command is javac.
    Variable
    A named storage location used to hold a value of a declared type.
    Data type
    A classification that determines which values a variable can hold and which operations are valid.
    Primitive type
    One of Java’s eight built-in value types: byte, short, int, long, float, double, char and boolean.
    Reference type
    A type whose variables refer to objects or arrays rather than directly holding a primitive value.
    Operator
    A symbol or keyword that performs an operation, such as +, ==, && or =.
    Conditional statement
    A statement such as if/else or switch that chooses which code runs based on a condition.
    Loop
    A control structure that repeats code, such as for, while or do-while.
    Method
    A named block of code that can accept parameters and may return a result.
    Parameter and argument
    A parameter is a variable in a method declaration; an argument is the actual value supplied when calling it.
    Array
    A fixed-length object that stores multiple values of one declared element type, accessed by zero-based index.
    Class
    A blueprint that declares the fields, constructors and methods associated with a kind of object.
    Object
    A runtime instance of a class, with state represented by fields and behavior represented by methods.
    Constructor
    A special class member used to initialize a new object; it has the class name and no return type.
    Encapsulation
    The practice of keeping an object’s internal state controlled and exposing suitable operations through methods.
    Collection
    An object or framework abstraction for grouping and working with multiple elements, such as a List or Set.
    Exception
    An object representing an event that interrupts the normal flow of program execution.
    Recursion
    A technique in which a method calls itself, normally with a base case that stops further calls.
    Algorithm complexity
    A description of how an algorithm’s time or memory requirements grow as input size increases, often using Big-O notation.

    1. Operators and expression tracing

    Know arithmetic (+ - * / %), comparisons, logical operators, assignment operators and increment/decrement. Integer division discards the fractional part; operator precedence determines grouping.

    int a = 7 / 2;       // 3
    int b = 7 % 2;       // 1
    int x = 4;
    int y = x++ + ++x;   // 4 + 6 = 10; x is 6

    Exam habit: trace each statement in order. Parentheses make intent clearer; avoid complicated expressions with multiple side effects in production code.

    2. Strings

    String objects are immutable: a method such as toUpperCase() returns a string; it does not change the original object. Use equals for text equality, not ==.

    String a = "java";
    String b = a.toUpperCase();
    System.out.println(a);          // java
    System.out.println(b);          // JAVA
    System.out.println("java".equals(a)); // true

    Learn length(), charAt(), substring(), contains(), indexOf(), split(), trim()/strip(), and StringBuilder for repeated modifications.

    3. Scope, defaults and casting

    Local variables must be assigned before use. Instance fields receive default values (numeric zero, false, or null for references). Narrowing conversions can lose information.

    double price = 9.8;
    int whole = (int) price; // 9
    int n = 5;
    double d = n;            // 5.0, widening

    Distinguish local variables, parameters, instance fields and static class fields. A variable declared inside a block is not accessible outside that block.

    4. Constructors and access

    A constructor initializes an object and has the same name as its class, with no return type. If you declare no constructor, Java supplies a no-argument default constructor; once you declare one, that automatic constructor is not supplied.

    class Student {
        private String name;
        Student(String name) {
            this.name = name;
        }
        String getName() { return name; }
    }

    private restricts access to the class; package-private has no modifier; protected and public have broader access rules. Prefer private fields and controlled methods.

    5. Packages, imports and static

    A package organizes related types and helps define access boundaries. The package declaration, when present, comes before imports. import lets you refer to a type by its simple name. static members belong to the class rather than an individual object.

    import java.util.Scanner;
    
    class Counter {
        static int total = 0;
        Counter() { total++; }
    }

    final on a variable means it can be assigned only once; on a method it prevents overriding; on a class it prevents subclassing.

    6. Recursion and algorithm basics

    Recursion is a method calling itself. Every recursive solution needs a base case and progress toward that case. A loop is often simpler for basic repetition.

    static int factorial(int n) {
        if (n < 0) throw new IllegalArgumentException();
        if (n <= 1) return 1; // base case
        return n * factorial(n - 1);
    }

    Common complexity vocabulary: O(1) constant, O(n) linear, O(n²) quadratic. A loop inside a loop over the same input is often quadratic.

    Quick reference: common exam distinctions

    ConceptsDifference to state clearly
    == vs equals()For primitives, == compares values. For references, it tests whether references identify the same object. equals() checks logical equality when the class implements it.
    while vs do-whilewhile checks before its body and may run zero times. do-while checks after its body and runs at least once.
    Array vs ArrayListAn array has a fixed length and can store primitives directly. ArrayList grows dynamically and stores objects (use wrapper types such as Integer).
    Overloading vs overridingOverloading uses the same method name with different parameter lists. Overriding replaces inherited instance-method behaviour with a compatible implementation.
    throw vs throwsthrow actually throws an exception object; throws declares possible exceptions in a method signature.
    Compile-time vs runtime errorCompile-time errors prevent compilation (for example, a type mismatch). Runtime exceptions occur while executing (for example, indexing beyond an array).

    Exam-style questions with worked answers

    Q1. What is printed by System.out.println(5 + 2 * 3);?

    Answer: 11. Multiplication has higher precedence than addition: 5 + (2 * 3).

    Q2. Write a method that returns the number of even values in an integer array.

    Answer:

    static int countEven(int[] values) {
        int count = 0;
        for (int value : values) {
            if (value % 2 == 0) count++;
        }
        return count;
    }

    This takes O(n) time because each element is checked once. State how you want to handle a null array if the question asks about invalid input.

    Q3. Why can String s = null; s.length(); fail?

    Answer: s refers to no object. Calling an instance method through it throws NullPointerException. Check for null before dereferencing when null is a valid possibility.

    Q4. What is the difference between a class and an object?

    Answer: A class defines a type, its state and behaviour. An object is a runtime instance of that class with its own instance state.

    Q5. What is the output and why?
    int[] a = {2, 4, 6};
    System.out.println(a.length);
    System.out.println(a[0]);

    Answer: 3, then 2. Length is the number of elements; indexes start at zero.

    Practice checklist

    Next up

    Keep going when you are ready.

    Continue