UI24PC320CS · OOP THROUGH JAVA · UNIT I · ADD-ON · ORANGE
One name,
many values.
Class 3 met arrays in passing — one worked example, one crash preview. This add-on slows all the way down: every way Java lets you declare an array, every way it lets you fill one, two simple programs traced end to end, and the jagged register where every row has its own length.
Carry one question through this session: if int[] marks = new int[5]; creates five slots, what exactly is inside each slot before you put anything there? The answer is one rule, it never changes, and it explains half the "why is it printing 0?" confusions this batch will ever have.
ARRAYS ADD-ON · THE ROAD FOR TODAY
Stop counting variables. Start indexing.
Every array question in an exam — and every array bug on your machine — comes from one of four places: how it was declared, how it was filled, how it was walked, or where its bounds end. Today covers all four, slowly, with the terminal open.
BY THE END OF TODAY YOU CAN
- writeall four declaration styles — and say which one the deck (and every style guide) prefers, and why
- fillan array five different ways: defaults, index-by-index, literal,
new int[]{…}, and a loop - debugthe two classic crashes — index out of bounds and the
length-vs-length()confusion - builda jagged 2D array where every row has its own length — and walk it safely with
t[r].length
WHERE THIS SITS
TODAY'S TOPICS, IN ORDER
- The problem — five marks, five variables, one muddleSTORY
- Declaration — all 4 legal spellings, one preferredSYNTAX
- Initialisation — defaults, index, literal,
new int[]{…}, loopSYNTAX - Simple program — highest mark + average, tracedPROGRAM
- 2D arrays — the timetable grid, two different lengthsCONCEPT
- Jagged arrays — Krish's cricket registerCONCEPT
- Misconception patrol + locked notebook buildDRILL
ADD-ON SESSION · 11 PARTS · DUAL MODE · ZERO ASSETS
PART 3 · WHY ARRAYS EXIST
Diya has five marks. Watch what happens without an array.
Internal marks are out: DS 78, Java 91, Maths 64, DBMS 85, English 72. Diya wants the highest and the average. Her first instinct — five variables — works… until it doesn't.
THE PILE-OF-VARIABLES APPROACH — WATCH IT FALL APART, ONE PRESS AT A TIME
THE ARRAY WAY — ONE NAME, FIVE NUMBERED SLOTS: int[] marks
One name. Slots numbered from 0. The LAST slot is marks[4] — length 5, last index 4. Tattoo that.
One name on the shelf, numbered compartments inside. The compartments sit side by side in memory — that's why the index jump is instant.
The first slot is marks[0], not marks[1]. Length 5 means indexes 0–4. Most array crashes in this batch will be this one fact, forgotten.
Once created with 5 slots, ALWAYS 5 slots. No stretching. (Growable lists exist — they arrive in Unit 5, and they use arrays underneath.)
An int[] holds only ints. The type in the declaration is a promise the compiler enforces on every slot.
PART 4 · DECLARATION — EVERY LEGAL SPELLING
Four ways to say "shelf of ints". One is the keeper.
Java accepts several spellings for the same declaration — exams love asking which are legal. Here are all of them, typed and compiled, with the deck's verdict on each.
// DeclareTour.java — every legal array declaration, one filepublic class DeclareTour{ public static void main(String[] args) { // STYLE 1 — declare only (no shelf yet, just a name that CAN point at one) int[] a; // preferred: type[] name — "int-array called a" int b[]; // legal (C-style) — compiles, but read it aloud: ugly // STYLE 2 — declare AND create in one line (5 slots, all default) int[] marks = new int[5]; // STYLE 3 — declare AND fill with a literal (size counted FOR you) int[] quick = {78, 91, 64, 85, 72}; // STYLE 4 — anonymous array — the literal with its type spelled out a = new int[]{10, 20, 30}; // works AFTER declaration too System.out.println("marks has " + marks.length + " slots"); System.out.println("quick has " + quick.length + " slots"); System.out.println("a now has " + a.length + " slots"); }}{78, 91, 64, 85, 72} is ONLY legal on the declaration line. Split it — declare on one line, assign quick = {…}; later — and the compiler refuses. Later assignment needs STYLE 4's new int[]{…}.| STYLE | SPELLING | WHAT EXISTS AFTER IT | VERDICT |
|---|---|---|---|
| 1 · declare | int[] a; | A name only — no shelf yet, points at nothing | Preferred spelling — "int-array called a" |
| 1 · C-style | int a[]; | Same as above, older spelling | Legal; recognise it in exam code, don't write it |
| 2 · create | new int[5] | A real 5-slot shelf, every slot at its default | Use when you'll fill values later / from input |
| 3 · literal | {78, 91, 64} | Shelf created AND filled; size counted for you | Use when values are known — declaration line only |
| 4 · anonymous | new int[]{10, 20} | Same as 3, but legal anywhere — assignments, method args | The literal's grown-up form |
new int[3]{10, 20, 30} does not compile — Java refuses because the literal already announces its own size. Either new int[3] (empty, defaults) or new int[]{10, 20, 30} (filled, counted). Not both.
PART 5 · INITIALISATION — WHAT'S IN THE SLOTS
The slots are never empty. Ever.
The moment new int[5] runs, Java fills every slot with the type's default value — before your code touches it. That's the answer to the cover question. Then you overwrite the defaults, five different ways.
// FillTour.java — what's in the slots, and 5 ways to change itpublic class FillTour{ public static void main(String[] args) { // WAY 0 — do nothing: Java already filled the defaults int[] fresh = new int[3]; System.out.println("untouched slot: " + fresh[0]); // WAY 1 — index by index (any order you like) fresh[0] = 78; fresh[2] = 64; fresh[1] = 91; // WAY 2 — literal at declaration (Part 4, style 3) double[] fees = {1550.50, 890.0}; // WAY 3 — anonymous array, any time after declaration fresh = new int[]{5, 10, 15, 20}; // WAY 4 — a loop fills a pattern (indexes 0..length-1) int[] table7 = new int[5]; for (int i = 0; i < table7.length; i++) { table7[i] = 7 * (i + 1); } // WAY 5 — read: the for-each loop (no index to get wrong) for (int v : table7) { System.out.print(v + " "); } }}| SLOT TYPE | DEFAULT |
|---|---|
int / long / short / byte | 0 |
double / float | 0.0 |
char | '\u0000' (blank char) |
boolean | false |
String / any object | null — printing is fine, calling a method on it crashes |
Answer to the cover question: the slots hold the type's default value from the instant new runs. An int[] is born full of zeros — which is why a marks program that prints 0 usually means "you never wrote to that slot," not "the array is broken."
PART 6 · SIMPLE PROGRAM — HIGHEST & AVERAGE
Diya's report, done properly this time.
Part 3's problem, solved with the shelf: one loop finds the highest mark and adds up the total; one cast keeps the average honest. This is the exam's favourite "simple array program" — every line of it earns marks.
// MarksReport.java — Diya's five marks: highest + averagepublic class MarksReport{ public static void main(String[] args) { int[] marks = {78, 91, 64, 85, 72}; int highest = marks[0]; // start with slot 0, not 0 itself int total = 0; for (int i = 0; i < marks.length; i++) { if (marks[i] > highest) { highest = marks[i]; } total = total + marks[i]; } double average = (double) total / marks.length; System.out.println("highest : " + highest); System.out.println("average : " + average); }}highest = marks[0] and not 0? Marks can't go negative here, but the habit matters: seeding with slot 0 works for ANY data — temperatures, profit/loss, sensor readings — where 0 might already beat every real value.The loop pattern to memorise: seed → sweep → decide. Seed the answer from slot 0, sweep indexes 0 to length-1, decide per slot. Highest, lowest, total, search — the exam's whole array-program family is this one skeleton with a different if.
PART 7 · 2D ARRAYS — A SHELF OF SHELVES
Rows and columns: quiz[row][column], row first, always.
Three students, four quiz scores each — that's a grid. In Java a 2D array is literally an array whose slots hold arrays: quiz.length counts the ROWS, quiz[r].length counts the COLUMNS of row r. Nested loops walk it.
// GridTour.java — a shelf of shelves: rows first, columns secondpublic class GridTour{ public static void main(String[] args) { int[][] marks = new int[3][4]; // 3 rows × 4 columns, all 0 marks[0][0] = 78; // [row][column] — row FIRST int[][] quiz = { {8, 9, 7, 10}, // row 0 — Diya {6, 8, 9, 7}, // row 1 — Rohit {10, 9, 8, 9} // row 2 — Krish }; System.out.println("rows : " + quiz.length); System.out.println("columns : " + quiz[0].length); for (int r = 0; r < quiz.length; r++) { for (int c = 0; c < quiz[r].length; c++) { System.out.print(quiz[r][c] + " "); } System.out.println(); // new line after each row } }}| EXPRESSION | WHAT IT COUNTS / GIVES |
|---|---|
quiz.length | number of ROWS → 3 |
quiz[r].length | columns of row r → 4 |
quiz[r] | the WHOLE row r — itself an int[] |
quiz[c][r] | swapped indexes — compiles fine, wrong data or a crash. Row FIRST. |
The secret that unlocks jagged arrays: quiz[r] is a complete 1D array in its own right. A 2D array is not a grid carved in stone — it's an array OF arrays. Which raises a question: must every inner array be the same length? Next part says no.
PART 8 · JAGGED ARRAYS — ROWS OF DIFFERENT LENGTHS
Krish's cricket register: every week logs a different number of sessions.
Krish tracks his weekly cricket-practice attendance. Week 1 had 3 sessions, match week had just 1, week 3 had 4. Forcing that into a rectangle wastes slots — so Java lets each row be born separately, with its own length. That's a jagged array.
THE REGISTER, ROW BY ROW — ONE PRESS PER WEEK
Three rows, lengths 3 · 1 · 4. reg[w].length tells the truth per row — hard-code a 4 and week 2 crashes.
// CricketRegister.java — Krish's weekly practice attendance (jagged)public class CricketRegister{ public static void main(String[] args) { int[][] reg = new int[3][]; // 3 weeks — rows NOT born yet reg[0] = new int[]{45, 60, 30}; // week 1 · 3 sessions (min) reg[1] = new int[]{90}; // week 2 · match week, 1 session reg[2] = new int[]{40, 40, 50, 35}; // week 3 · 4 sessions for (int w = 0; w < reg.length; w++) { System.out.print("week " + (w + 1) + " (" + reg[w].length + " sessions): "); for (int m : reg[w]) // for-each never overshoots a short row { System.out.print(m + "min "); } System.out.println(); } }}new int[3][] is legal — rows come later. new int[][] and new int[][4] do NOT compile: Java must know how many row-slots to make, but each row's length can wait. And touching reg[0][0] before assigning row 0 throws a NullPointerException — the row-slot still holds null.
Why this matters beyond cricket: real data is jagged — marks per elective (different class sizes), stops per bus route, sessions per week. The rectangle is the special case; array-of-arrays is the truth, and reg[w].length is how you walk it without crashing.
PART 9 · MISCONCEPTION PATROL
Six claims. Call TRUE or FALSE before each verdict drops.
These six are the exact wrong beliefs that cost marks and cause crashes. Say your answer out loud (or write T/F in your notebook), then press for the verdict — one claim per press.
Five falses and one true — and every false is a real crash or a real red mark on a real answer sheet.
PART 10 · YOUR TURN — NOTEBOOK FIRST
Build your own register. Then — only then — unlock.
One activity, everything from this add-on in it: a jagged declaration, three different initialisations, a nested walk, and a running total. Write it in your notebook completely before touching the lock.
THE TASK Write MyRegister.java: store Krish's register — week 1: 45, 60, 30 · week 2: 90 · week 3: 40, 40, 50, 35 (minutes) — in a jagged int[][].
MUST PRINT Each week's total minutes on its own line, then the grand total. Expected: 135, 90, 165 — grand 390.
MUST USE new int[3][] for the outer array · reg[w].length or for-each for the walk · no hard-coded 3s inside the loops.
PREDICT Before running: what happens if you print reg[1][1]? Write your answer down — the solution sheet settles it.
Locked on purpose. Your notebook version first — wrong-then-corrected beats copied-and-forgotten, every time.
// MyRegister.java — jagged register + weekly totals + grand totalpublic class MyRegister{ public static void main(String[] args) { int[][] reg = new int[3][]; reg[0] = new int[]{45, 60, 30}; reg[1] = new int[]{90}; reg[2] = new int[]{40, 40, 50, 35}; int grand = 0; for (int w = 0; w < reg.length; w++) { int weekTotal = 0; for (int m : reg[w]) { weekTotal = weekTotal + m; } grand = grand + weekTotal; System.out.println("week " + (w + 1) + " total: " + weekTotal + " min"); } System.out.println("grand total : " + grand + " min"); }}| MARK YOURSELF | /100 |
|---|---|
Jagged declaration via new int[3][] | 25 |
| Three rows assigned, correct lengths 3·1·4 | 25 |
Loops driven by length — no hard-coded sizes | 25 |
| Weekly totals + grand total correct (135/90/165/390) | 15 |
| PREDICT answered correctly before running | 10 |
PART 11 · CLOSE — WHAT LEAVES THE ROOM WITH YOU
One name, many values — and you now own every spelling of it.
- SHELFAn array is one name over numbered slots, side by side in memory. First index 0, last index
length−1, size fixed at birth. - DECLAREFour spellings —
int[] a;(the keeper),int a[];(legal, avoid),new int[5], and the literal{78, 91, 64}. Size + literal together = compile error. - DEFAULTSSlots are never empty: 0 / 0.0 /
false/'\u0000'/nullfrom the instantnewruns. - FILLFive ways — do nothing (defaults), index by index, literal, anonymous
new int[]{…}, loop-fill. Read back with for-each when you don't need the index. - PROGRAMSeed → sweep → decide: highest, total, average — one skeleton, cast
(double)BEFORE dividing. - 2D
quiz[row][column], row first.quiz.length= rows,quiz[r].length= that row's columns,quiz[r]is a whole 1D array. - JAGGED
new int[3][]— first dimension compulsory, rows born separately with their own lengths. Krish's register: 3 · 1 · 4. Unassigned row =null.
java-practice\ tree, one folder per session — this add-on slots in beside class-03\, where arrays were first met.Where this pays off next: Unit 2's exception classes catch ArrayIndexOutOfBoundsException by NAME, Lab 4 walks stack traces from a crashing array walk, and Unit 5's growable collections are arrays wearing a coat. Everything jagged you built today is load-bearing.