ISC Computer Science · Class XII

Objects & Classes
Complete Study Guide

Everything you need to ace your ISC exam — theory, examples, code, and practice questions. All in one place.

4
Core Topics
15+
Code Examples
10
Quiz Questions
100
Target Score
01

Objects — Data (Attributes) & Behaviour (Methods)

Java is a pure object-oriented language. Everything revolves around objects and the classes they belong to. Understanding this relationship is the foundation of the entire syllabus topic.

Definition — Object
An object is a real-world entity that has state (data/attributes) and behaviour (operations/methods). In Java, an object is a specific instance of a class that occupies memory at runtime.
Definition — Class
A class is a blueprint or template that defines the common properties (fields) and behaviours (methods) that all objects of that type will possess. A class does not occupy memory by itself — only objects do.

📦 Attributes (Data / State)

These are the instance variables declared inside a class. Each object has its own copy. They represent the state of the object at any given moment.


Example: A Car object has attributes: color, speed, brand, model.

⚙️ Methods (Behaviour)

These are the functions defined inside a class that operate on the object's data. They represent what an object can do.


Example: A Car object has methods: accelerate(), brake(), honk().

🔑
Key Relationship: Class vs Object

Class is the cookie-cutter; Object is the cookie. You can bake many cookies (objects) using one cookie-cutter (class). A class is a compile-time concept; an object is a runtime reality.

Class (Blueprint)
Student
↓ instantiation
Object / Instance
s1
name = "Aarav"
roll = 101
marks = 92
Object / Instance
s2
name = "Priya"
roll = 102
marks = 87
Object / Instance
s3
name = "Rahul"
roll = 103
marks = 95
Student.java Java
// CLASS DEFINITION — the blueprint
class Student {
    // ─── ATTRIBUTES (instance variables / data) ───
    String name;
    int    rollNo;
    double marks;

    // ─── METHODS (behaviour) ───
    void display() {
        System.out.println("Name: " + name + "  Roll: " + rollNo + "  Marks: " + marks);
    }

    void promote() {
        if (marks >= 40)
            System.out.println(name + " is PROMOTED!");
        else
            System.out.println(name + " needs to reappear.");
    }
}

// CREATING OBJECTS (instances) in main
class Main {
    public static void main(String[] args) {
        Student s1 = new Student();  // s1 is an OBJECT / INSTANCE
        s1.name   = "Aarav";           // accessing attribute
        s1.rollNo = 101;
        s1.marks  = 92.5;
        s1.display();                   // calling method

        Student s2 = new Student();  // another independent object
        s2.name   = "Priya";
        s2.rollNo = 102;
        s2.marks  = 87.0;
        s2.display();
        s2.promote();
    }
}
Object as an Instance of a Class

When you write Student s1 = new Student();s1 is an instance (object) of the class Student. The new keyword allocates memory on the heap and returns a reference. s1 holds that reference (memory address).

Concept Class Object
Nature Template / Blueprint Real entity in memory
Memory No memory allocated Memory allocated on heap
Keyword class new
Creation time Compile time Runtime
Count One class Many objects per class
Example Student class s1, s2, s3
⭐ Exam Tips — Section 1
  • Definition question: Always mention "blueprint/template", "state (attributes)", and "behaviour (methods)" in your definition.
  • When asked to differentiate class vs object: memory allocation is the key differentiator.
  • The dot operator (.) is used to access attributes and methods of an object.
  • new keyword: (a) allocates heap memory, (b) calls the constructor, (c) returns a reference.
02

Constructors

A constructor is a special method that is automatically called when an object is created using new. It initialises the object's attributes to meaningful values.

Definition — Constructor
A constructor is a special member method of a class that has the same name as the class, has no return type (not even void), and is automatically invoked when an object is created using the new keyword.

Types of Constructors

① Default Constructor

Takes no parameters. Initialises all instance variables to default values (0, null, false). If you don't write any constructor, Java provides one automatically.

② Parameterised Constructor

Takes parameters to initialise the object with specific values at the time of creation. Most commonly used in ISC programs.

③ Copy Constructor

Takes an object of the same class as parameter and creates a duplicate with the same field values.

Box.java — All Constructor Types Java
class Box {
    double length, width, height;

    // ① DEFAULT CONSTRUCTOR — no parameters
    Box() {
        length = 1.0;
        width  = 1.0;
        height = 1.0;
        System.out.println("Default constructor called");
    }

    // ② PARAMETERISED CONSTRUCTOR
    Box(double l, double w, double h) {
        length = l;
        width  = w;
        height = h;
        System.out.println("Parameterised constructor called");
    }

    // ③ COPY CONSTRUCTOR — takes object of same class
    Box(Box b) {
        length = b.length;
        width  = b.width;
        height = b.height;
        System.out.println("Copy constructor called");
    }

    double volume() {
        return length * width * height;
    }
}

class Main {
    public static void main(String[] args) {
        Box b1 = new Box();          // default constructor
        Box b2 = new Box(3.0, 4.0, 5.0); // parameterised
        Box b3 = new Box(b2);         // copy constructor

        System.out.println("b1 volume: " + b1.volume()); // 1.0
        System.out.println("b2 volume: " + b2.volume()); // 60.0
        System.out.println("b3 volume: " + b3.volume()); // 60.0
    }
}

The this Keyword in Constructors

💡
this — Refers to the Current Object

this is a reference variable that always points to the current object of the class. It is commonly used when parameter names shadow (overlap with) instance variable names inside constructors.

using this keyword Java
class Circle {
    double radius;
    String color;

    // Without 'this' → parameter names SAME as field names → AMBIGUITY!
    Circle(double radius, String color) {
        this.radius = radius;  // this.radius = instance var; radius = param
        this.color  = color;
    }

    double area() {
        return Math.PI * this.radius * this.radius;
    }
}

Constructor Overloading

🔄
Constructor Overloading

Having multiple constructors in the same class with different parameter lists is called constructor overloading. Java differentiates them by the number, type, or order of parameters — this is decided at compile time.

Feature Constructor Method
Name Same as class name Any valid identifier
Return type None (not even void) Must have a return type
Called Automatically with new Explicitly by the programmer
Purpose Initialise the object Perform operations on the object
Inheritance Not inherited Inherited (unless private/static)
⭐ Exam Tips — Constructors
  • Must mention: same name as class, no return type, auto-called with new.
  • If you define any parameterised constructor, Java NO LONGER provides the default — you must write it yourself if needed.
  • this() can be used to call one constructor from another (constructor chaining). It must be the FIRST statement.
  • Constructors CANNOT be static, abstract, final, or synchronized.
  • Common ISC question: "Differentiate between constructor and method" — answer using the table above.
03

Real-World Programming Examples

OOP shines when we model real-world entities. ISC exams frequently ask you to identify classes, objects, attributes, and methods from a given scenario. Here are the most common examples with complete code.

🏦 Example 1: BankAccount

A bank account has state (balance, account number) and behaviour (deposit, withdraw, check balance).

BankAccount.java Java
class BankAccount {
    // ATTRIBUTES
    private int    accNo;
    private String holderName;
    private double balance;

    // CONSTRUCTOR
    BankAccount(int accNo, String name, double initialBalance) {
        this.accNo      = accNo;
        this.holderName = name;
        this.balance    = initialBalance;
    }

    // METHODS (behaviour)
    void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    void withdraw(double amount) {
        if (amount > 0 && amount <= balance)
            balance -= amount;
        else
            System.out.println("Insufficient funds!");
    }

    void display() {
        System.out.println("Acc: " + accNo + "  Name: " + holderName + "  Bal: " + balance);
    }
}

class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount(1001, "Aarav", 5000.0);
        acc.deposit(2000.0);
        acc.withdraw(500.0);
        acc.display();   // Acc: 1001  Name: Aarav  Bal: 6500.0
    }
}

👔 Example 2: Employee (with salary calculation)

A classic ISC-style problem with basic computation inside a class.

Employee.java Java
class Employee {
    int    empId;
    String name;
    double basicSalary;
    double hra, da, grossSalary;

    Employee(int id, String n, double basic) {
        empId       = id;
        name        = n;
        basicSalary = basic;
        hra         = 0.20 * basicSalary; // 20%
        da          = 0.10 * basicSalary; // 10%
        grossSalary = basicSalary + hra + da;
    }

    void displayDetails() {
        System.out.println("ID     : " + empId);
        System.out.println("Name   : " + name);
        System.out.println("Basic  : " + basicSalary);
        System.out.println("HRA    : " + hra);
        System.out.println("DA     : " + da);
        System.out.println("Gross  : " + grossSalary);
    }
}

class Main {
    public static void main(String[] args) {
        Employee e1 = new Employee(201, "Priya Sharma", 30000);
        e1.displayDetails();
    }
}

Common Real-World → OOP Mapping (ISC Exam Patterns)

Real-World Entity Class Name Attributes (Data) Methods (Behaviour)
🚗 Car Car brand, model, speed, fuel accelerate(), brake(), refuel()
📚 Book Book title, author, price, pages display(), calculateDiscount()
🎓 Student Student name, rollNo, marks[], grade calcAverage(), display(), promote()
🏦 Bank BankAccount accNo, balance, holderName deposit(), withdraw(), display()
⚽ Player Player name, age, goals, country scoreGoal(), display()
📱 Mobile Mobile brand, model, ram, storage call(), sendSms(), display()
⭐ Exam Tips — Real-World Examples
  • When asked to "identify classes and objects from a scenario", look for nouns → likely classes; verbs → likely methods.
  • Instance variables are usually private (data hiding / encapsulation) — accessed via getters/setters.
  • Attributes represent WHAT the object IS; methods represent WHAT the object DOES.
  • In ISC exams, the program pattern is: define class → constructor → methods → test in main. Always follow this structure.
04

Basic Input/Output — Scanner & PrintStream

Java uses stream-based I/O. For standard console I/O in ISC programs, you use Scanner (from java.util) for input and System.out (PrintStream) for output.

Scanner Class
Part of java.util package. Reads text input from keyboard (or file) and parses it into primitive types and strings using various next*() methods.
System.out (PrintStream)
System.out is an object of PrintStream class. It provides print(), println(), and printf() to send output to the console.

Creating a Scanner Object

Scanner Setup Java
import java.util.Scanner;  // Step 1: import

class InputDemo {
    public static void main(String[] args) {

        // Step 2: Create Scanner object linked to System.in (keyboard)
        Scanner sc = new Scanner(System.in);

        // Reading different data types
        System.out.print("Enter name: ");
        String name = sc.nextLine();       // reads full line including spaces

        System.out.print("Enter age: ");
        int age = sc.nextInt();            // reads integer

        System.out.print("Enter salary: ");
        double salary = sc.nextDouble();  // reads double

        System.out.print("Enter grade: ");
        char grade = sc.next().charAt(0); // reads char (Scanner has no nextChar)

        // OUTPUT using println and printf
        System.out.println("Name: " + name);
        System.out.printf("Age: %d  Salary: %.2f  Grade: %c%n", age, salary, grade);

        sc.close(); // good practice: close scanner when done
    }
}

Complete Scanner Method Reference

Method Returns Reads Notes
nextInt() int Next integer token Stops at whitespace
nextLong() long Next long integer Stops at whitespace
nextDouble() double Next decimal number Stops at whitespace
nextFloat() float Next float value Stops at whitespace
nextBoolean() boolean true or false Case-insensitive
next() String Next word (token) Stops at whitespace
nextLine() String Entire line Stops at newline (\n)
hasNext() boolean Returns true if more input exists
hasNextInt() boolean Checks if next token is an int
close() void Closes the scanner/stream

Output Methods — PrintStream

Method Behaviour New Line?
System.out.print(x) Prints x No
System.out.println(x) Prints x then newline Yes
System.out.printf(fmt, args) Formatted output (C-style) Only if %n or \n used
⚠️
The nextLine() Pitfall — VERY COMMON ISC TRAP!

After calling nextInt(), nextDouble() etc., a newline character (\n) remains in the buffer. The next nextLine() call immediately reads that empty newline instead of waiting. Fix: add an extra sc.nextLine(); after any nextInt() / nextDouble() before calling nextLine().

nextLine Pitfall Fix Java
int age = sc.nextInt();
sc.nextLine();                  // ← consume leftover newline
String address = sc.nextLine(); // ← now reads correctly
⭐ Exam Tips — Scanner I/O
  • Always write import java.util.Scanner; at the top — forgetting this loses marks.
  • Scanner must be connected to System.in for keyboard input: new Scanner(System.in).
  • No nextChar() in Scanner — use sc.next().charAt(0) to read a character.
  • System.out is a static final field of the System class, of type PrintStream.
05

Input/Output Exceptions

Exceptions are runtime errors that disrupt normal program flow. Java has a robust exception-handling mechanism using try-catch-finally. ISC focuses specifically on I/O exceptions with Scanner.

Definition — Exception
An exception is an abnormal condition that arises during program execution. Java provides a hierarchy of exception classes, all descending from java.lang.Throwable. Exceptions can be checked (must be handled/declared) or unchecked (runtime exceptions).

Key Exceptions in I/O Context

🚨 InputMismatchException

Thrown by Scanner when the token read does NOT match the expected type. E.g., user types "hello" when nextInt() is called.


Unchecked java.util

📭 NoSuchElementException

Thrown when the input stream is exhausted (end of input) but Scanner tries to read more tokens.


Unchecked java.util

📁 IOException

Thrown during file/stream I/O failures — file not found, read/write errors. Parent class for most I/O exceptions.


Checked java.io

🔒 IllegalStateException

Thrown when a method (like Scanner.next()) is called after the Scanner has been closed.


Unchecked java.lang

ExceptionHandling.java Java
import java.util.Scanner;
import java.util.InputMismatchException;

class ExceptionDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        try {
            System.out.print("Enter an integer: ");
            int n = sc.nextInt();   // may throw InputMismatchException
            System.out.println("Square = " + (n * n));
        }
        catch (InputMismatchException e) {
            System.out.println("Error: Please enter a valid integer!");
            System.out.println("Details: " + e.getMessage());
        }
        catch (Exception e) {
            // generic catch-all
            System.out.println("Unexpected error: " + e);
        }
        finally {
            sc.close();            // always executes — close resources
            System.out.println("Scanner closed.");
        }
    }
}

try-catch-finally Structure

Block Purpose Executes When
try Contains code that might throw an exception Always
catch(ExType e) Handles the specified exception type Only if that exception is thrown in try
finally Cleanup code (close files, scanners) Always — even if exception occurs
⭐ Exam Tips — Exceptions
  • finally ALWAYS runs — even if return is in try or catch.
  • Multiple catch blocks: most specific exception must come BEFORE the more general one.
  • InputMismatchException is in java.util; IOException is in java.io.
  • Closing Scanner in finally is best practice — mention it in answers.
06

Tokens, Whitespace & StringTokenizer

Understanding how Java reads input as tokens is critical for both Scanner and StringTokenizer questions in ISC exams.

Definition — Token
A token is the smallest meaningful unit extracted from a stream of text. In a Scanner or StringTokenizer context, tokens are words or values separated by delimiters (commonly whitespace characters).
Definition — Whitespace
Whitespace is the collective name for invisible characters that separate tokens: space (' '), tab ('\t'), newline ('\n'), carriage return ('\r'), and form feed ('\f'). Scanner uses whitespace as the default delimiter.
💡
How Scanner Tokenises Input

When you type "Hello World 42", Scanner sees 3 tokens: Hello, World, 42. All whitespace between them is ignored. next() reads one token; nextLine() reads the entire line (including spaces) as one string.

StringTokenizer Class

Definition — StringTokenizer
StringTokenizer (in java.util) is a legacy class that breaks a string into tokens based on a specified delimiter. Unlike String.split(), it provides methods to iterate over tokens without creating a full array.

Constructors of StringTokenizer

Constructor Delimiter Return tokens as delimiters?
StringTokenizer(String s) Whitespace (default) No
StringTokenizer(String s, String delim) Custom delimiter string No
StringTokenizer(String s, String delim, boolean returnDelims) Custom delimiter string Yes/No based on flag

Key Methods of StringTokenizer

Method Return Type Description
hasMoreTokens() boolean Returns true if more tokens remain
nextToken() String Returns the next token as a String
nextToken(String delim) String Changes delimiter and returns next token
countTokens() int Returns the number of tokens remaining
hasMoreElements() boolean Same as hasMoreTokens() (from Enumeration)
nextElement() Object Same as nextToken() but returns Object
StringTokenizer — Complete Examples Java
import java.util.StringTokenizer;

class TokenDemo {
    public static void main(String[] args) {

        // ─── EXAMPLE 1: Default delimiter (whitespace) ───
        String s1 = "Hello World Java Programming";
        StringTokenizer st1 = new StringTokenizer(s1);

        System.out.println("Total tokens: " + st1.countTokens()); // 4
        while (st1.hasMoreTokens()) {
            System.out.println(st1.nextToken());
        }
        // Output: Hello / World / Java / Programming (one per line)

        // ─── EXAMPLE 2: Custom delimiter (",") ───
        String s2 = "Aarav,Priya,Rahul,Sneha";
        StringTokenizer st2 = new StringTokenizer(s2, ",");

        System.out.println("Names count: " + st2.countTokens()); // 4
        while (st2.hasMoreTokens()) {
            System.out.print(st2.nextToken() + " | ");
        }
        // Output: Aarav | Priya | Rahul | Sneha |

        // ─── EXAMPLE 3: Multiple delimiters ───
        String s3 = "10+20-30*40";
        StringTokenizer st3 = new StringTokenizer(s3, "+-*");
        while (st3.hasMoreTokens()) {
            System.out.print(st3.nextToken() + " ");
        }
        // Output: 10 20 30 40

        // ─── EXAMPLE 4: Word count in a sentence ───
        String sentence = "ISC exams are not that hard";
        StringTokenizer st4 = new StringTokenizer(sentence);
        System.out.println("Word count = " + st4.countTokens()); // 6
    }
}

StringTokenizer vs String.split() vs Scanner

Feature StringTokenizer String.split() Scanner
Package java.util java.lang java.util
Returns Tokens via iterator String array Tokens via next*()
Delimiter One char from a set Regex pattern Any pattern (default: whitespace)
Empty tokens Skipped Included Skipped
Input source String only String only Any InputStream / String
Speed Fast (legacy) Medium Medium
ISC Pattern — Reading CSV data with StringTokenizer Java
import java.util.*;

class CSVReader {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter student data (name,roll,marks): ");
        String line = sc.nextLine();

        StringTokenizer st = new StringTokenizer(line, ",");

        String name  = st.nextToken();
        int    roll  = Integer.parseInt(st.nextToken().trim());
        double marks = Double.parseDouble(st.nextToken().trim());

        System.out.println("Name: "  + name);
        System.out.println("Roll: "  + roll);
        System.out.println("Marks: " + marks);
        sc.close();
    }
}
⭐ Exam Tips — Tokens & StringTokenizer
  • Always import java.util.StringTokenizer; or import java.util.*;
  • Standard pattern: while(st.hasMoreTokens()) { String tok = st.nextToken(); ... }
  • countTokens() returns remaining count — it changes as you call nextToken().
  • After nextToken() exhausts all tokens, calling it again throws NoSuchElementException.
  • Use Integer.parseInt() and Double.parseDouble() to convert String tokens to numbers.
  • StringTokenizer delimiter is a set of characters — each character in the delim string is a delimiter, not the whole string as a unit.

⚡ Quick Reference — Last Minute Revision

Object
Instance of class. Has state (attributes) + behaviour (methods). Created with new.
Class
Blueprint. No memory by itself. Contains fields + methods. Keyword: class.
Constructor
Same name as class. No return type. Auto-called with new. Types: default, parameterised, copy.
this
Reference to current object. Resolves name conflicts between params and instance vars.
Scanner setup
import java.util.Scanner;Scanner sc = new Scanner(System.in);
Read char
sc.next().charAt(0) — no nextChar() in Scanner!
nextLine trap
After nextInt(): call sc.nextLine() first to consume leftover \n.
InputMismatchException
Thrown by Scanner when wrong data type is entered. In java.util.
finally block
Always executes — even after exception or return. Use for cleanup.
Token
Smallest unit in input. Separated by whitespace (or custom delimiter).
StringTokenizer
new StringTokenizer(str, delim) → use hasMoreTokens() + nextToken() loop.
countTokens()
Returns remaining tokens. Decreases with each nextToken() call.

🎯 Practice Quiz

Test your understanding — answer each question before revealing the answer!

Q1 of 10
Which of the following is TRUE about constructors in Java?
Q2 of 10
What does the new keyword do in Java?
Q3 of 10
Which Scanner method reads an entire line of input, including spaces?
Q4 of 10
What exception does Scanner throw when the token does NOT match the expected data type?
Q5 of 10
How do you read a char using Scanner in Java? (Scanner has no nextChar())
Q6 of 10
In a StringTokenizer, what does countTokens() return?
Q7 of 10
What is the output of: new StringTokenizer("a,,b", ",").countTokens() ?
Q8 of 10
The finally block in Java:
Q9 of 10
What is this in Java?
Q10 of 10
Which package must be imported to use StringTokenizer?