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.
📦 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().
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.
roll = 101
marks = 92
roll = 102
marks = 87
roll = 103
marks = 95
// 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(); } }
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 … |
- 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. newkeyword: (a) allocates heap memory, (b) calls the constructor, (c) returns a reference.
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.
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.
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 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.
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
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) |
- 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, orsynchronized. - Common ISC question: "Differentiate between constructor and method" — answer using the table above.
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).
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.
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() |
- 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.
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.
java.util package. Reads text input from keyboard (or file) and parses it into primitive types and strings using various next*() methods.System.out is an object of PrintStream class. It provides print(), println(), and printf() to send output to the console.Creating a Scanner Object
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 |
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().
int age = sc.nextInt(); sc.nextLine(); // ← consume leftover newline String address = sc.nextLine(); // ← now reads correctly
- Always write
import java.util.Scanner;at the top — forgetting this loses marks. - Scanner must be connected to
System.infor keyboard input:new Scanner(System.in). - No
nextChar()in Scanner — usesc.next().charAt(0)to read a character. System.outis a static final field of theSystemclass, of typePrintStream.
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.
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
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 |
finallyALWAYS runs — even ifreturnis intryorcatch.- Multiple
catchblocks: most specific exception must come BEFORE the more general one. InputMismatchExceptionis injava.util;IOExceptionis injava.io.- Closing Scanner in
finallyis best practice — mention it in answers.
Tokens, Whitespace & StringTokenizer
Understanding how Java reads input as tokens is critical for both Scanner and StringTokenizer questions in ISC exams.
' '), tab ('\t'), newline ('\n'), carriage return ('\r'), and form feed ('\f'). Scanner uses whitespace as the default delimiter.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
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 |
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 |
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(); } }
- Always
import java.util.StringTokenizer;orimport java.util.*; - Standard pattern:
while(st.hasMoreTokens()) { String tok = st.nextToken(); ... } countTokens()returns remaining count — it changes as you callnextToken().- After
nextToken()exhausts all tokens, calling it again throwsNoSuchElementException. - Use
Integer.parseInt()andDouble.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
new.class.new. Types: default, parameterised, copy.import java.util.Scanner; → Scanner sc = new Scanner(System.in);sc.next().charAt(0) — no nextChar() in Scanner!nextInt(): call sc.nextLine() first to consume leftover \n.java.util.new StringTokenizer(str, delim) → use hasMoreTokens() + nextToken() loop.nextToken() call.🎯 Practice Quiz
Test your understanding — answer each question before revealing the answer!
new keyword do in Java?char using Scanner in Java? (Scanner has no nextChar())countTokens() return?new StringTokenizer("a,,b", ",").countTokens() ?finally block in Java:this in Java?StringTokenizer?