📘 CHAPTER 1: Introduction to Java & Object-Oriented Programming (OOP)
🔹 What is Java?
Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned
by Oracle).
It is platform-independent — meaning “write once, run anywhere”.
Java is widely used for web apps, mobile apps (especially Android), enterprise software, and games.
🔹 Key Features of Java
Feature Explanation
Platform-Independent Runs on any OS using JVM (Java Virtual Machine)
Object-Oriented Uses objects to structure programs
Secure Strong type-checking and memory management
Robust Handles errors and memory leaks well
Multithreaded Can perform many tasks at once
Portable Runs on any machine with JVM
🔹 Java Editions
Edition Use
Java SE (Standard Edition) General desktop applications
Java EE (Enterprise Edition) Web and enterprise applications
Java ME (Micro Edition) Mobile devices (older platforms)
🔹 Basic Java Program Structure
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld → Defines the class
main () → Entry point of any Java program
System.out.println() → Prints output to console
🔹 What is Object-Oriented Programming (OOP)?
OOP is a way to organize programs using objects (real-world entities).
Four Pillars of OOP:
Concept Meaning Example
Encapsulation Hides internal data using classes and access Bank account balance is private
methods
Inheritance A class can get features from another class Dog inherits from Animal
Polymorphism Same method acts differently in different classes draw() can draw shapes or lines
Abstraction Show only essential details Car interface shows steering, not engine
code
🔹 Java Program Execution Process
1. Write code in .java file.
2. Compile using javac HelloWorld.java → creates .class file (bytecode).
3. Run using java HelloWorld.
Bytecode runs on JVM, which makes Java platform-independent.
🔹 Advantages of Java
Easy to learn.
Free and open source.
Huge community and library support.
Used in many industries.
🔹 Disadvantages of Java
Slower than low-level languages (like C++).
Consumes more memory.
GUI development can be verbose.
📌 Summary
Java is platform-independent, object-oriented, and widely used.
Programs are structured using classes, objects, and methods.
Java follows the OOP paradigm to build reusable and organized code.
🧠 Flashcards
Q: What does JVM stand for?
A: Java Virtual Machine.
Q: What is the main method in Java?
A: public static void main(String[] args).
Q: Name the four pillars of OOP.
A: Encapsulation, Inheritance, Polymorphism, Abstraction.
Q: What makes Java platform-independent?
A: Its bytecode runs on the JVM.
Q: What is the file extension for a compiled Java file?
A: .class
📘 CHAPTER 2: Data Types, Variables, and Constants in Java
🔹 What is a Variable?
A variable is a named memory location that stores a value. The value can change during program execution.
int age = 25;
int → data type
age → variable name
25 → value stored
🔹 Java Data Types
Java has two categories of data types:
1. Primitive Data Types (8 types):
Type Size Example Use For
Int 4 bytes int x = 10; Whole numbers
double 8 bytes double pi = 3.14; Decimals
char 2 bytes char ch = 'A'; Single characters
boolean 1 bit boolean isJava = true; True/False
byte 1 byte byte b = 100; Small integers
short 2 bytes short s = 2000; Small integers
long 8 bytes long l = 100000L; Big integers
float 4 bytes float f = 1.23f; Small decimal
2. Non-Primitive (Reference) Types
Examples: String, Arrays, Classes, Objects
String name = "Alice";
🔹 Declaring Variables
int score; // Declaration
score = 85; // Assignment
int age = 20; // Declaration + Assignment
Multiple declarations:
int x = 5, y = 10, z = 15;
🔹 Constants in Java
Use final keyword to declare a constant (value cannot change).
final double PI = 3.14159;
Convention: Constant names are written in ALL CAPS.
🔹 Type Conversion
1. Implicit (Widening) Conversion:
Small → Big type (safe)
int x = 10;
double y = x; // OK
2. Explicit (Narrowing) Conversion:
Big → Small type (may lose data)
double d = 9.8;
int i = (int) d; // Must cast
🔹 Java Literals
Integer literal: int x = 100;
Floating-point literal: double pi = 3.14;
Character literal: char ch = 'A';
Boolean literal: boolean isOn = true;
String literal: String name = "Joyce";
🔹 Variable Naming Rules
Must start with a letter, _, or $
Cannot start with a digit
Case-sensitive (age ≠ Age)
No Java keywords (like int, class)
✅ Good: studentAge, totalMarks
❌ Bad: 2score, class
🔹 Advantages of Using Constants
Improves code readability
Prevents accidental changes
Easy to update values in one place
🔹 Common Mistakes
Mistake What Happens
Using wrong type Compilation error
Forgetting to initialize Runtime error
Wrong cast Data loss or error
📌 Summary
Java has 8 primitive types and supports reference types like String.
Variables hold values; constants use final.
Java automatically converts smaller types to larger; explicit casting is needed otherwise.
🧠 Flashcards
Q: What are the 4 integer types in Java?
A: byte, short, int, long
Q: Which keyword is used for constants?
A: final
Q: What is the size of char in Java?
A: 2 bytes
Q: What’s the difference between float and double?
A: float is smaller (4 bytes), double is larger (8 bytes)
Q: Give an example of implicit type conversion.
A: int x = 5; double y = x;
📘 CHAPTER 3: Methods, Parameters, and Return Values in Java
🔹 What is a Method?
A method is a block of code that performs a specific task. It’s also called a function in other languages.
public static void greet() {
System.out.println("Hello!");
You can call a method like this:
greet ();
🔹 Why Use Methods?
Avoid repeating code (DRY principle — Don't Repeat Yourself)
Organize code into logical parts
Reuse code across multiple programs
🔹 Method Structure
public static int add (int a, int b) {
return a + b;
Part Meaning
public static Access and scope (for now, always use this in main)
int Return type
add Method name
int a, int b Parameters
return Gives result back to caller
🔹 Method Calling
int result = add (5, 3); // result = 8
🔹 Return Values
A method can return a value or void (no return).
Example: Method with return
public static double square (double x) {
return x * x;
Example: Void method
public static void sayHello () {
System.out.println("Hi!");
}
🔹 Parameters and Arguments
Term Meaning
Parameter Variable in method definition
Argument Actual value passed to method
// Parameter: int num
public static void show (int num) {
System.out.println(num);
// Argument: 25
show (25);
🔹 Method Overloading
Method overloading means creating multiple methods with the same name but different parameters.
public static int multiply (int a, int b) {
return a * b;
public static double multiply (double a, double b) {
return a * b;
}
✅ Java automatically picks the correct version based on the arguments.
🔹 Examples of Methods
1. Method to calculate area:
public static double areaOfCircle (double r) {
return 3.14 * r * r;
}
2. Method to check even or odd:
public static boolean isEven (int n) {
return n % 2 == 0;
🔹 Advantages of Using Methods
Advantage Explanation
Code Reuse Use one method in many places
Modularity Easier to test and manage
Clarity Break large programs into parts
🔹 Common Errors with Methods
Error Reason
No return statement For non-void methods
Wrong return type Method says int, but returns String
Mismatched parameters Argument types don't match method definition
📌 Summary
Methods make code reusable and organized.
They can accept parameters and return values.
Overloading lets you use the same method name with different inputs.
🧠 Flashcards
Q: What is a method in Java?
A: A block of code that performs a task.
Q: What does void mean in a method?
A: The method does not return a value.
Q: What is method overloading?
A: Multiple methods with the same name but different parameters.
Q: Give an example of a return statement.
A: return a + b;
Q: What’s the difference between a parameter and an argument?
A: A parameter is in the method definition; an argument is passed during the call.
📘 CHAPTER 4: Classes, Objects, and Constructors in Java
🔹 What is a Class?
A class is a blueprint or template for creating objects.
It defines fields (data/variables) and methods (actions).
public class Student {
String name;
int age;
void displayInfo() {
System.out.println(name + " is " + age + " years old.");
🔹 What is an Object?
An object is an instance of a class.
It has state (variables) and behavior (methods).
Student s1 = new Student();
s1.name = "Jane";
s1.age = 20;
s1.displayInfo();
🔹 Creating and Using Objects
Step Code
Declare class class Car { int speed; }
Create object Car c1 = new Car();
Set data c1.speed = 50;
Access method c1.showSpeed();
🔹 Constructors in Java
A constructor is a special method that runs automatically when an object is created.
public class Dog {
Dog() {
System.out.println("Dog object created");
Dog d1 = new Dog(); // Output: Dog object created
🔹 Constructor Features
Feature Details
Name Same as class
No return type Not even void
Called automatically When object is created
🔹 Types of Constructors
1. Default Constructor:
No parameters.
public Student() {
name = "Default";
age = 0;
2. Parameterized Constructor:
Accepts values.
public Student(String n, int a) {
name = n;
age = a;
3. Constructor Overloading:
Multiple constructors with different parameters.
public Student() { }
public Student(String n) { name = n; }
public Student(String n, int a) { name = n; age = a; }
🔹 The this Keyword
this refers to the current object.
Used to avoid confusion when variable names overlap.
public Student(String name) {
this.name = name; // refers to the object's field
🔹 Example: Class with Constructor
public class Book {
String title;
int pages;
Book(String t, int p) {
title = t;
pages = p;
void showBook() {
System.out.println(title + " has " + pages + " pages.");
Book b = new Book("Java 101", 300);
b.showBook();
🔹 Advantages of OOP (Using Classes and Objects)
Advantage Benefit
Modularity Divide program into small parts
Code Reusability Use same class many times
Security Use private fields, public methods
Easy Maintenance Code is easier to update and fix
🔹 Common Errors
Problem Why It Happens
No constructor Java provides default one
Wrong parameter types Constructor call must match
Calling method on null object You forgot to use new
📌 Summary
Class = Blueprint
Object = Instance
Constructor = Initializes objects
Use this to refer to current object’s fields.
🧠 Flashcards
Q: What is a class in Java?
A: A template for creating objects.
Q: What is a constructor?
A: A special method that initializes objects.
Q: How do you create an object?
A: ClassName obj = new ClassName();
Q: What does this refer to?
A: The current object.
Q: Can constructors be overloaded?
A: Yes, using different parameter lists.
📘 CHAPTER 5: Decision Making in Java (if, else, switch)
🔹 Why Do We Use Decision Making?
Sometimes, programs need to make choices. For example:
"If age is over 18, allow voting. Otherwise, deny."
Java provides several decision-making structures to handle such cases.
🔹 if Statement
Executes a block of code only if a condition is true.
int age = 20;
if (age >= 18) {
System.out.println("You can vote.");
}
🔹 if...else Statement
Runs one block if condition is true, another if false.
if (age >= 18) {
System.out.println("Eligible to vote.");
} else {
System.out.println("Not eligible.");
}
🔹 if...else if...else
Used when you have multiple conditions.
int score = 75;
if (score >= 90) {
System.out.println("Grade A");
} else if (score >= 70) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
🔹 Comparison Operators
Operator Meaning Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater or equal x >= y
<= Less or equal x <= y
🔹 Logical Operators
Operator Meaning Example
&& AND x > 10 && y < 20
` `
! NOT !(x == y)
🔹 The switch Statement
The switch is useful when checking a variable against many fixed values.
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Invalid day");
}
Rules:
break stops checking.
default runs if no match is found.
🔹 Nested if Statements
You can place one if inside another:
if (x > 0) {
if (x < 100) {
System.out.println("x is between 1 and 99");
}
}
🔹 Ternary Operator
Short-hand for if...else:
String result = (age >= 18) ? "Adult" : "Minor";
System.out.println(result);
🔹 Common Mistakes
Mistake What Happens
Missing break All following cases execute
Using == for Strings Doesn’t compare text properly
Forgetting braces {} Only one line is considered part of if
📌 Summary
Use if, else if, and else to check multiple conditions.
Use switch for fixed options (like menu choices).
Use ternary operator for simple decisions.
🧠 Flashcards
Q: What does if do?
A: Executes code only if the condition is true.
Q: What is switch used for?
A: Checking one variable against many possible values.
Q: What does break do in switch?
A: Stops checking other cases.
Q: What is the syntax of the ternary operator?
A: condition ? true_result : false_result
Q: What is the difference between == and = in Java?
A: == compares values; = assigns values.
📘 CHAPTER 6: Loops in Java (while, do-while, for)
🔹 Why Use Loops?
Loops let you repeat a block of code multiple times, which saves time and avoids repetition.
Example: Print numbers from 1 to 10.
🔹 Types of Loops in Java
Loop Type Use When...
while You don’t know how many times to repeat, but condition is known.
do-while You want the loop to run at least once.
for You know exactly how many times to repeat.
🔹 The while Loop
Repeats as long as the condition is true.
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
🔹 The do-while Loop
Runs the body at least once, then checks condition.
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
Use do-while when the loop must run at least one time, even if the condition is false.
🔹 The for Loop
Used when you know the starting, ending, and step value.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Structure:
for (initialization; condition; update) {
// body
}
🔹 Loop Example: Print Even Numbers from 2 to 10
for (int i = 2; i <= 10; i += 2) {
System.out.println(i);
}
🔹 Nested Loops
You can put a loop inside another loop.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i=" + i + " j=" + j);
}
}
🔹 The break Statement
Used to exit a loop early.
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
System.out.println(i);
}
Output: 1 2 3 4
🔹 The continue Statement
Skips the current iteration and continues with the next.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
Output: 1 2 4 5 (3 is skipped)
🔹 Infinite Loops
Loops that never end (accidental or intentional):
while (true) {
// endless loop
}
🔹 Common Mistakes
Mistake What Happens
Forgetting i++ Loop runs forever
Wrong condition Loop never runs
Using = instead of == Assignment instead of comparison
📌 Summary
for → Best when you know the count
while → Check condition first
do-while → Runs at least once
Use break to exit early, continue to skip current step
🧠 Flashcards
Q: Which loop always runs at least once?
A: do-while
Q: What is the syntax of a for loop?
A: for (init; condition; update) { }
Q: What does continue do?
A: Skips the current loop iteration.
Q: What does break do in a loop?
A: Exits the loop immediately.
Q: Can you nest loops in Java?
A: Yes, one loop can be inside another.
📘 CHAPTER 7: Strings, Characters, and StringBuilder in Java
🔹 What is a String?
A String is a sequence of characters enclosed in double quotes.
String name = "Java";
Java treats strings as objects of the String class.
🔹 Creating Strings
String s1 = "Hello"; // String literal
String s2 = new String("Hi"); // Using constructor
🔹 Common String Methods
Method Purpose Example
length() Returns number of characters s.length()
charAt(index) Returns character at index s.charAt(0) = 'H'
toUpperCase() Converts to uppercase s.toUpperCase()
toLowerCase() Converts to lowercase s.toLowerCase()
equals() Compares contents s1.equals(s2)
equalsIgnoreCase() Compares ignoring case s1.equalsIgnoreCase(s2)
substring(start, end) Extract part of string "Java".substring(1,3) = "av"
indexOf(char) Finds position of char "Hello".indexOf'e') = 1
trim() Removes whitespace " Java ".trim() = "J(ava"
🔹 String Comparison
✅ Use. equals () to compare contents
String a = "hello";
String b = "hello";
System.out.println(a.equals(b)); // true
❌ Avoid using == for comparing string values
String x = new String("hi");
String y = new String("hi");
System.out.println(x == y); // false (compares memory)
🔹 Immutability of Strings
Strings in Java are immutable — once created, they cannot be changed.
String a = "Hello";
a = a + " World"; // Creates a new String object
🔹 char Data Type
A char stores a single character using single quotes 'A'.
char letter = 'B';
🔹 Useful char Methods (with Character wrapper class)
Method Use
Character.isDigit('5') true
Character.isLetter('A') True
Character.toUpperCase('b') 'B'
Character.toLowerCase('X') 'x'
🔹 StringBuilder: Efficient String Modification
Use StringBuilder when you need to change strings repeatedly (faster than String).
StringBuilder sb = new StringBuilder("Java");
sb.append(" Rocks");
System.out.println(sb); // Java Rocks
🔹 Common StringBuilder Methods
Method Use
append() Adds text at the end
insert(index, text) Inserts at position
delete(start, end) Removes characters
reverse() Reverses the text
toString() Converts back to String
🔹 Example: Reverse a String Using StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.reverse();
System.out.println(sb); // "olleH"
🔹 Advantages of StringBuilder
Advantage Explanation
Mutable Can change value without creating new object
Efficient Faster when modifying strings multiple times
Easy to use Provides simple methods for editing text
📌 Summary
String is immutable; StringBuilder is mutable.
Use .equals() for comparing string values.
Use char for single characters and Character for utilities.
🧠 Flashcards
Q: Are strings mutable in Java?
A: No, they are immutable.
Q: Which class allows mutable strings?
A: StringBuilder
Q: How do you compare strings in Java?
A: Using .equals() or .equalsIgnoreCase()
Q: How do you reverse a string with StringBuilder?
A: .reverse() method
Q: What is the difference between == and .equals() for strings?
A: == compares memory; .equals() compares actual text.
📘 CHAPTER 8: Arrays and Advanced Array Concepts in Java
🔹 What is an Array?
An array is a collection of variables of the same type, stored in contiguous memory.
Think of an array as a list or container that holds multiple values under one name.
int[] numbers = {10, 20, 30, 40};
🔹 Array Declaration and Initialization
int[] marks = new int[5]; // declares array of size 5
marks[0] = 80;
marks[1] = 90;
Shortcut:
int[] marks = {80, 90, 70, 60, 85};
🔹 Accessing Array Elements
System.out.println(marks[0]); // prints first element
Index starts from 0
marks.length gives number of elements
🔹 Looping Through Arrays
for (int i = 0; i < marks.length; i++) {
System.out.println(marks[i]);
}
Or using for-each loop:
for (int score : marks) {
System.out.println(score);
}
🔹 Types of Arrays
1. One-Dimensional Array
List of values
String[] cities = {"Lagos", "Abuja", "Kano"};
2. Two-Dimensional Array
Like a table (rows × columns)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // 6
🔹 Jagged Arrays (Arrays of Arrays)
A 2D array where rows can have different lengths.
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[1];
🔹 Arrays with Objects
You can create arrays of objects too:
Student[] students = new Student[3];
students[0] = new Student("Ali", 20);
🔹 Common Mistakes with Arrays
Mistake What Happens
Accessing out-of-range index ArrayIndexOutOfBoundsException
Using wrong loop limit Skips or crashes
Forgetting new for object arrays NullPointerException
🔹 Advantages of Arrays
Advantage Description
Easy access Use index to get any value
Memory-efficient Continuous memory block
Loop-friendly Works well with loops
🔹 Disadvantages of Arrays
Disadvantage Reason
Fixed size Cannot change size once created
Same data type Cannot mix types like in lists
📌 Summary
Arrays store multiple values of the same type.
Use [ ] to declare, access, and loop through them.
Java supports 1D, 2D, and jagged arrays.
for-each is useful for clean loops.
🧠 Flashcards
Q: What is the index of the first array element?
A: 0
Q: What exception occurs if you access index out of bounds?
A: ArrayIndexOutOfBoundsException
Q: What loop is best for arrays?
A: for or for-each
Q: How do you declare a 2D array?
A: int[][] matrix = new int[2][3];
Q: Can arrays store objects?
A: Yes
📘 CHAPTER 9: Inheritance and Polymorphism in Java
🔹 What is Inheritance?
Inheritance is an object-oriented principle where a class (child/subclass) can inherit properties and behaviors
from another class (parent/superclass).
It promotes code reuse and logical hierarchy.
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks.");
}
}
Dog d = new Dog();
d.eat(); // Inherited method
d.bark(); // Child class method
🔹 Types of Inheritance (in Java)
Type Supported? Description
Single ✅ Yes One subclass inherits from one superclass
Multilevel ✅ Yes Subclass inherits from another subclass
Hierarchical ✅ Yes Multiple subclasses inherit from one superclass
Multiple ❌ No Not supported directly (Java uses interfaces instead)
🔹 super Keyword
Used to access members of the superclass (parent class).
super.methodName(); // calls method from parent class
super.variableName; // accesses parent's variable
🔹 Constructor Chaining with super()
class Animal {
Animal() {
System.out.println("Animal created");
}
}
class Dog extends Animal {
Dog() {
super(); // calls parent constructor
System.out.println("Dog created");
}
}
🔹 Method Overriding
A child class redefines a method from the parent class.
Use @Override annotation to show it's intentional.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
🔹 What is Polymorphism?
Polymorphism means "many forms."
A single method behaves differently depending on the object that calls it.
Animal a = new Cat(); // Parent reference
a.sound(); // Calls overridden method in Cat
Polymorphism allows runtime decision-making.
🔹 Types of Polymorphism
Type Description Example
Compile-time (Method Same method name, different add(int, int) and add(double,
Overloading) parameters double)
Runtime (Method Overriding) Method in child overrides parent sound() method in Cat class
🔹 Final Keyword
Use Example
Final variable (cannot change) final int x = 10;
Final method (cannot override) final void show() {}
Final class (cannot be extended) final class MathUtils {}
🔹 Abstract Classes
Cannot be instantiated
Can contain abstract methods (no body)
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
🔹 Interfaces
An interface defines methods without bodies (all abstract). A class must implement the interface.
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
Interfaces support multiple inheritance in Java.
🔹 Differences: Inheritance vs Polymorphism
Inheritance Polymorphism
"Is-a" relationship "Many forms" behavior
One class inherits another One method, many behaviors
Promotes code reuse Promotes flexibility
📌 Summary
Inheritance lets a class use features from another.
Polymorphism allows the same method to behave differently.
Java supports overriding, interfaces, and abstract classes for flexibility.
🧠 Flashcards
Q: What is inheritance in Java?
A: One class gaining features from another.
Q: What does super do?
A: Refers to the parent class.
Q: What is method overriding?
A: Redefining a method from the parent in the child class.
Q: What is polymorphism?
A: Same method behaves differently for different objects.
Q: What is the keyword for preventing inheritance?
A: final