Skip to content

Information Technology · Ch 2 — Programming

Programming Fundamentals — A Quick Review

1

Programming Fundamentals — A Quick Review

In the first year you learned to write simple Java programs — declaring variables, using operators, taking decisions with if/switch, repeating work with loops, and organising code into methods. This chapter builds directly on that foundation, so we begin with a short review to fix the vocabulary we will keep using.

The shape of a Java program

Every Java program lives inside a class, and execution begins in the special method main. The source code you type (a .java file) is turned into bytecode by the compiler javac, and the Java Virtual Machine (JVM) then runs that bytecode — the reason the same program runs on any computer ("write once, run anywhere").

public class Review {
    public static void main(String[] args) {
        int a = 12, b = 5;
        System.out.println("Sum = " + (a + b));   // Sum = 17
        System.out.println("a > b ? " + (a > b));  // a > b ? true
    }
}

Objects and classes — the idea we now deepen

A class is a blueprint that groups data (called fields or instance variables) together with the methods that act on that data. An object is a real thing created from that blueprint using new. For example, a Student class describes what every student has (name, marks) and what every student can do (display details); each actual student is an object.

class Student {
    String name;                 // field
    int marks;                   // field

    void display() {             // method (behaviour)
        System.out.println(name + " scored " + marks);
    }
}

public class Demo {
    public static void main(String[] args) {
        Student s = new Student();   // create an object
        s.name = "Rina";
        s.marks = 88;
        s.display();                 // Rina scored 88
    }
}

Second-year programming is mostly about writing better classes: controlling who may touch a field (access specifiers), reusing one class to build another (inheritance), and using ready-made library classes instead of reinventing them. We then move from Java to building web pages with HTML. Keep this object-and-class picture in mind — every topic that follows rests on it.

Definition 1Class

A blueprint that groups data (fields) with the methods that operate on that data; objects are created from it.

Definition 2Object

A concrete instance created from a class using the new keyword, holding its own copy of the fields.

Definition 3Field (instance variable)

A variable declared inside a class that stores an object's data.

Definition 4Method

A named block of code inside a class that defines an object's behaviour; it may take parameters and return a value.