Home
1Introducing OOP & Java Basics
1

Topic 1 of 13 · Lecture 1

Introducing OOP & Java Basics

What object-oriented programming is, how it differs from structured programming, and the Java building blocks: data types, variables, operators and decisions.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

A banking app stores two million accounts. Where does each balance live — and who is allowed to change it?

In a structured program, every function can reach every piece of data, so one careless line anywhere can corrupt a balance. Object-oriented programming (OOP) groups each account’s data together with the only methods allowed to touch it.

This topic introduces that idea and the Java basics we will use to express it: types, variables, operators and decisions.

Concept 1 of 8

Two ways to organise a program

Structured code shares global data between functions; OOP packs data and behaviour into objects.

Concept 1 of 8

Two ways to organise a program (cont.)

Structured (procedural) programming

  • The program is a list of functions that run top-down.
  • Data is separate from the functions, often shared globally.
  • Languages: C, Pascal, Fortran.
  • Works well for small, linear tasks.

Object-oriented programming

  • The program is a set of objects that send messages to each other.
  • Each object keeps its own data private and exposes methods.
  • Languages: Java, C++, C#, Python.
  • Scales to large systems that change over time.

Concept 2 of 8

Classes, objects and the four pillars

A class is a blueprint; each object is one thing built from it, with its own field values.

Classes, objects and the four pillars

PillarIn one sentence
EncapsulationKeep an object’s data private; allow changes only through its methods.
InheritanceBuild a new class from an existing one and reuse its code (Student is a Person).
PolymorphismOne call, many behaviours: shape.area() works for circles and rectangles.
AbstractionShow what an object does, hide how it does it.

Concept 3 of 8

The Java platform: JDK, JRE and JVM

The JDK (developer kit) includes the JRE (runtime), which includes the JVM (virtual machine).

Concept 3 of 8

The Java platform: JDK, JRE and JVM

“Write once, run anywhere”: the same bytecode runs on every JVM.

The Java platform: JDK, JRE and JVM

  • javac Hello.java compiles source code into bytecode (Hello.class).
  • java Hello starts a JVM that loads, verifies and runs the bytecode, compiling hot code to machine code (JIT).

Code example

Your first Java program

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, GUB!");
        System.out.print("OOP ");
        System.out.println("in Java");
    }
}
Output
Hello, GUB!
OOP in Java
  • The file name must match the public class: Hello.java.
  • main is where the program starts. It is public (the JVM can call it) and static (no object is needed to call it).
  • println ends the line; print does not.

Concept 4 of 8

Primitive data types

TypeSizeRange / exampleDefault
byte8 bits−128 to 1270
short16 bits−32,768 to 32,7670
int32 bitsabout ±2.1 billion (231 − 1 = 2,147,483,647)0
long64 bits±9.2 × 1018 — write 10_000_000_000L0L
float32 bits~7 significant digits — write 3.14f0.0f
double64 bits~15 significant digits — 3.140.0
char16 bitsone Unicode character — 'A' (value 65)'\u0000'
boolean—true or false onlyfalse
Note: String is not a primitive — it is a class. Primitives hold a value directly; everything else is an object reached through a reference.

Concept 5 of 8

Variables, literals and type conversion

Widening conversions happen automatically (no data lost). Going the other way needs an explicit cast.

Concept 5 of 8

Variables, literals and type conversion (cont.)

int age = 20;            // declare + initialise
final double PI = 3.14159; // constant
char grade = 'A';
boolean passed = true;
long big = 9_000_000_000L;
var name = "Rahim";      // type inferred: String

double d = age;          // widening: automatic
int i = (int) 9.99;      // narrowing: cast → 9
char next = (char) (grade + 1);  // 'B'
  • Casting a double to int truncates (drops the fraction).
  • Casting to a smaller integer type keeps only the low bits, so values wrap around.
  • In expressions, byte/short/char are promoted to int first.

Interactive

Type casting and overflow

Concept 6 of 8

Operators

GroupOperatorsExample → result
Arithmetic+ − * / %17 / 5 → 3, 17 % 5 → 2, 17.0 / 5 → 3.4
Increment / decrement++ −−x++ uses then adds; ++x adds then uses
Relational== != < > <= >=5 >= 5 → true
Logical&& || !a > 0 && b > 0 (short-circuit)
Assignment= += −= *= /= %=x += 3 is x = x + 3
Ternarycond ? a : bm >= 40 ? "Pass" : "Fail"
Bitwise / shift& | ^ ~ << >>5 & 3 → 1, 1 << 4 → 16
Precedence: Precedence, high to low: ++ -- ! → * / % → + - → relational → == != → && → || → ?: → assignment. Use parentheses when in doubt.

Step through the code

Trace: evaluating expressions

Press Next to run one line at a time and watch every variable change. Predict each value before you click.

Step through the code

Trace: evaluating expressions (cont.)

Interactive

Operator playground

Code example

Reading input with Scanner

import java.util.Scanner;

public class AddTwo {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("First number: ");
        int a = in.nextInt();
        System.out.print("Second number: ");
        int b = in.nextInt();
        System.out.println("Sum = " + (a + b));
        System.out.println("Avg = " + (a + b) / 2.0);
    }
}
Console (user typed 7 and 8)
First number: 7
Second number: 8
Sum = 15
Avg = 7.5

Code example

Reading input with Scanner (cont.)

  • nextInt(), nextDouble(), next() (one word), nextLine() (whole line).
  • Why the brackets in "Sum = " + (a + b)? Without them, "Sum = " + a becomes a String first and you would print Sum = 78.

Concept 7 of 8

Decisions: if, else if, else

An if-else chooses exactly one of two paths.

Decisions: if, else if, else

int marks = 72;
if (marks >= 80) {
    System.out.println("A+");
} else if (marks >= 70) {
    System.out.println("A");   // runs
} else if (marks >= 60) {
    System.out.println("A-");
} else {
    System.out.println("Below A-");
}
  • Conditions are checked top to bottom; the first true branch runs and the rest are skipped.
  • The condition must be a boolean — if (x = 5) does not compile in Java.

Interactive

if-else ladder in action

Concept 8 of 8

The switch statement

int day = 3;
switch (day) {
    case 1:  System.out.println("Sat"); break;
    case 2:  System.out.println("Sun"); break;
    case 3:  System.out.println("Mon"); break;
    default: System.out.println("Other");
}

// Java 14+: arrow form, no fall-through, can return a value
String type = switch (day) {
    case 6, 7 -> "Weekend";
    default   -> "Weekday";
};
  • switch works on int, char, String, enums and their wrappers — not on double or boolean.
  • Without break, execution falls through into the next case.
  • default runs when no case matches.
  • Use switch for one variable compared with fixed values; use if for ranges like marks >= 80.

Interactive

switch and fall-through

Worked example 1 of 3

Worked example 1

What does System.out.println(7 / 2 + 7 % 2 + 7 / 2.0); print?
Show the solution
  1. 7 / 2 = 3 (integer division).
  2. 7 % 2 = 1.
  3. 7 / 2.0 = 3.5 (a double operand).
  4. 3 + 1 + 3.5 = 7.5

Worked example 2 of 3

Worked example 2

Write one line that stores the larger of a and b in max.
Show the solution
int max = (a > b) ? a : b;
The ternary operator picks one of two values. Math.max(a, b) does the same.

Worked example 3 of 3

Worked example 3

What is printed? int x = 10; x += x++ + ++x; System.out.println(x);
Show the solution
  1. x += E means x = x + E; the left x is read first: 10.
  2. x++ gives 10, x becomes 11.
  3. ++x makes x 12 and gives 12.
  4. x = 10 + (10 + 12) = 32.

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. Which primitive type would you use for a student ID like 2233051012? Why?
Show the answer
long — 2,233,051,012 is larger than the int maximum (2,147,483,647). (A String is also fine because we never do arithmetic on IDs.)
2. Evaluate (double) (5 / 2) and (double) 5 / 2.
Show the answer
2.0 and 2.5. In the first, integer division happens before the cast.
3. What is the value of (byte) 130?
Show the answer
−126. 130 − 256 = −126.

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. Write an if-else that prints “Leap” for leap years.
Show the answer
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
    System.out.println("Leap");
else
    System.out.println("Not leap");
5. A switch on month (1–12) must print the number of days. How can fall-through help?
Show the answer
Group cases with no break between them: case 4: case 6: case 9: case 11: days = 30; break; and case 2: days = 28; break;, default 31.
6. Give two differences between OOP and structured programming.
Show the answer
OOP bundles data with methods in objects (structured code keeps them separate); OOP hides data with access control (structured code often shares global data); OOP supports inheritance and polymorphism for reuse.

Check yourself

Quiz

Summary

Summary

  • OOP organises programs as objects that bundle data with behaviour; structured programming separates functions from data.
  • javac compiles .java to bytecode; the JVM runs bytecode on any platform.
  • Eight primitives: byte, short, int, long, float, double, char, boolean. Everything else is an object.
  • int / int is integer division; casting narrows with truncation or wrap-around.
  • if-else checks conditions top-down; switch compares one value against constants and falls through without break.