Unit 1 home
UNIT-1 ADD-ON · ARRAYS EVERY DECLARATION · EVERY INITIALISATION · JAGGED UNIT I · UI24PC320CS
ARRAYS ADD-ON · P 1/11PGDN NEXT POINT · PGUP BACK

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.

C3 · SCANNER + TYPES + ARRAYS (FIRST LOOK) ADD-ON · ARRAYS, PROPERLY UNIT 2 · ARRAYS OF OBJECTS EVERYWHERE
THE HOOKDiya has 5 marks — and was about to declare 5 variables
TODAY'S SPAN4 declaration styles · 5 ways to fill · 2 traced programs · 2D · jagged
ACTIVITY1 locked notebook build — Krish's cricket-practice jagged register
FEEDSUnit 2 directly — BankAccount[] (Lab 4) and every collection after it

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

int m1 = 78; int m2 = 91; int m3 = 64; int m4 = 85; int m5 = 72; int m6 = …? a 6th subject next sem = EDIT EVERY LINE

THE ARRAY WAY — ONE NAME, FIVE NUMBERED SLOTS: int[] marks

78
marks[0]
91
marks[1]
64
marks[2]
85
marks[3]
72
marks[4]

One name. Slots numbered from 0. The LAST slot is marks[4] — length 5, last index 4. Tattoo that.

An array is a shelf

One name on the shelf, numbered compartments inside. The compartments sit side by side in memory — that's why the index jump is instant.

Index starts at 0

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.

Size is fixed at birth

Once created with 5 slots, ALWAYS 5 slots. No stretching. (Growable lists exist — they arrive in Unit 5, and they use arrays underneath.)

One type per shelf

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 — ALL 4 STYLES, COMPILED
1// DeclareTour.java — every legal array declaration, one file
2public class DeclareTour
3{
4 public static void main(String[] args)
5 {
6 // STYLE 1 — declare only (no shelf yet, just a name that CAN point at one)
7 int[] a; // preferred: type[] name — "int-array called a"
8 int b[]; // legal (C-style) — compiles, but read it aloud: ugly
9 // STYLE 2 — declare AND create in one line (5 slots, all default)
10 int[] marks = new int[5];
11 // STYLE 3 — declare AND fill with a literal (size counted FOR you)
12 int[] quick = {78, 91, 64, 85, 72};
13 // STYLE 4 — anonymous array — the literal with its type spelled out
14 a = new int[]{10, 20, 30}; // works AFTER declaration too
15 System.out.println("marks has " + marks.length + " slots");
16 System.out.println("quick has " + quick.length + " slots");
17 System.out.println("a now has " + a.length + " slots");
18 }
19}
TERMINAL — REAL RUN
$ javac DeclareTour.java
$ java DeclareTour
marks has 5 slots
quick has 5 slots
a now has 3 slots
length has NO brackets on an array — it's a field, not a method. Strings use length() WITH brackets. Exams test exactly this.
One trap on STYLE 3: the brace literal {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[]{…}.
STYLESPELLINGWHAT EXISTS AFTER ITVERDICT
1 · declareint[] a;A name only — no shelf yet, points at nothingPreferred spelling — "int-array called a"
1 · C-styleint a[];Same as above, older spellingLegal; recognise it in exam code, don't write it
2 · createnew int[5]A real 5-slot shelf, every slot at its defaultUse when you'll fill values later / from input
3 · literal{78, 91, 64}Shelf created AND filled; size counted for youUse when values are known — declaration line only
4 · anonymousnew int[]{10, 20}Same as 3, but legal anywhere — assignments, method argsThe literal's grown-up form
Never write a size AND a literal together.

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 — DEFAULTS FIRST, THEN EVERY FILL STYLE
1// FillTour.java — what's in the slots, and 5 ways to change it
2public class FillTour
3{
4 public static void main(String[] args)
5 {
6 // WAY 0 — do nothing: Java already filled the defaults
7 int[] fresh = new int[3];
8 System.out.println("untouched slot: " + fresh[0]);
9 // WAY 1 — index by index (any order you like)
10 fresh[0] = 78; fresh[2] = 64; fresh[1] = 91;
11 // WAY 2 — literal at declaration (Part 4, style 3)
12 double[] fees = {1550.50, 890.0};
13 // WAY 3 — anonymous array, any time after declaration
14 fresh = new int[]{5, 10, 15, 20};
15 // WAY 4 — a loop fills a pattern (indexes 0..length-1)
16 int[] table7 = new int[5];
17 for (int i = 0; i < table7.length; i++)
18 {
19 table7[i] = 7 * (i + 1);
20 }
21 // WAY 5 — read: the for-each loop (no index to get wrong)
22 for (int v : table7)
23 {
24 System.out.print(v + " ");
25 }
26 }
27}
TERMINAL — REAL RUN
$ javac FillTour.java && java FillTour
untouched slot: 0
7 14 21 28 35
Line 8 printed 0 BEFORE any assignment — proof the defaults are real. int → 0, double → 0.0, boolean → false, String (any object) → null.
SLOT TYPEDEFAULT
int / long / short / byte0
double / float0.0
char'\u0000' (blank char)
booleanfalse
String / any objectnull — 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 — ONE LOOP, TWO ANSWERS
1// MarksReport.java — Diya's five marks: highest + average
2public class MarksReport
3{
4 public static void main(String[] args)
5 {
6 int[] marks = {78, 91, 64, 85, 72};
7 int highest = marks[0]; // start with slot 0, not 0 itself
8 int total = 0;
9 for (int i = 0; i < marks.length; i++)
10 {
11 if (marks[i] > highest)
12 {
13 highest = marks[i];
14 }
15 total = total + marks[i];
16 }
17 double average = (double) total / marks.length;
18 System.out.println("highest : " + highest);
19 System.out.println("average : " + average);
20 }
21}
TERMINAL — REAL RUN
$ javac MarksReport.java && java MarksReport
highest : 91
average : 78.0
Line 17 is the C3 truncation trap, defused: total is 390, and (double) casts BEFORE dividing. Write total / marks.length without the cast and Java does int division — the decimals vanish silently the moment the total isn't a clean multiple of 5.
Why 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 — 3 STUDENTS × 4 QUIZZES
1// GridTour.java — a shelf of shelves: rows first, columns second
2public class GridTour
3{
4 public static void main(String[] args)
5 {
6 int[][] marks = new int[3][4]; // 3 rows × 4 columns, all 0
7 marks[0][0] = 78; // [row][column] — row FIRST
8 int[][] quiz =
9 {
10 {8, 9, 7, 10}, // row 0 — Diya
11 {6, 8, 9, 7}, // row 1 — Rohit
12 {10, 9, 8, 9} // row 2 — Krish
13 };
14 System.out.println("rows : " + quiz.length);
15 System.out.println("columns : " + quiz[0].length);
16 for (int r = 0; r < quiz.length; r++)
17 {
18 for (int c = 0; c < quiz[r].length; c++)
19 {
20 System.out.print(quiz[r][c] + " ");
21 }
22 System.out.println(); // new line after each row
23 }
24 }
25}
TERMINAL — REAL RUN
$ javac GridTour.java && java GridTour
rows : 3
columns : 4
8 9 7 10
6 8 9 7
10 9 8 9
Outer loop picks the row, inner loop walks its columns. Read quiz[1][3] aloud as "row 1, column 3" → Rohit's 4th quiz → 7.
EXPRESSIONWHAT IT COUNTS / GIVES
quiz.lengthnumber of ROWS → 3
quiz[r].lengthcolumns 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

reg[0] · wk 1456030
reg[1] · wk 290
reg[2] · wk 340405035

Three rows, lengths 3 · 1 · 4. reg[w].length tells the truth per row — hard-code a 4 and week 2 crashes.

CricketRegister.java — ROWS BORN SEPARATELY
1// CricketRegister.java — Krish's weekly practice attendance (jagged)
2public class CricketRegister
3{
4 public static void main(String[] args)
5 {
6 int[][] reg = new int[3][]; // 3 weeks — rows NOT born yet
7 reg[0] = new int[]{45, 60, 30}; // week 1 · 3 sessions (min)
8 reg[1] = new int[]{90}; // week 2 · match week, 1 session
9 reg[2] = new int[]{40, 40, 50, 35}; // week 3 · 4 sessions
10 for (int w = 0; w < reg.length; w++)
11 {
12 System.out.print("week " + (w + 1) + " (" + reg[w].length + " sessions): ");
13 for (int m : reg[w]) // for-each never overshoots a short row
14 {
15 System.out.print(m + "min ");
16 }
17 System.out.println();
18 }
19 }
20}
TERMINAL — REAL RUN
$ javac CricketRegister.java && java CricketRegister
week 1 (3 sessions): 45min 60min 30min
week 2 (1 sessions): 90min
week 3 (4 sessions): 40min 40min 50min 35min
Line 6 is the whole trick: new int[3][] gives the FIRST dimension only. Each reg[w] is null until you assign it a real row — of any length you like.
The first dimension is compulsory.

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.

"The first element of marks is marks[1]."
Length 5 → indexes 0, 1, 2, 3, 4. The FIRST slot is marks[0]; marks[5] is the crash.
FALSE — starts at 0
"You get the size with marks.length() — brackets, like a method."
On arrays, length is a FIELD: marks.length, no brackets. (Strings flip it: s.length() IS a method. Exams adore this swap.)
FALSE — no brackets
"int[] a = new int[3]{1, 2, 3}; is legal — size plus values."
Size AND literal together is a compile error. Give the size OR the values — the values already count themselves.
FALSE — pick one
"A slot of new int[5] you never assigned holds garbage."
Part 5's terminal proved it: Java fills defaults at birth — 0, 0.0, false, '\u0000', null. Never garbage.
FALSE — default 0
"Every row of a 2D array must have the same length."
Krish's register says otherwise: a 2D array is an array OF arrays, and each row is born separately — 3, 1, 4 sessions.
FALSE — jagged is legal
"Once created with 5 slots, an array stays 5 slots forever."
Correct — size is fixed at birth. "Growing" means creating a NEW array and re-pointing the name (Part 5's WAY 3 did exactly that).
TRUE — fixed at birth

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.

SOLUTION SHEET — COMPARE, DON'T COPY
MyRegister.java — ONE CLEAN ANSWER
1// MyRegister.java — jagged register + weekly totals + grand total
2public class MyRegister
3{
4 public static void main(String[] args)
5 {
6 int[][] reg = new int[3][];
7 reg[0] = new int[]{45, 60, 30};
8 reg[1] = new int[]{90};
9 reg[2] = new int[]{40, 40, 50, 35};
10 int grand = 0;
11 for (int w = 0; w < reg.length; w++)
12 {
13 int weekTotal = 0;
14 for (int m : reg[w])
15 {
16 weekTotal = weekTotal + m;
17 }
18 grand = grand + weekTotal;
19 System.out.println("week " + (w + 1) + " total: " + weekTotal + " min");
20 }
21 System.out.println("grand total : " + grand + " min");
22 }
23}
TERMINAL — REAL RUN
$ javac MyRegister.java && java MyRegister
week 1 total: 135 min
week 2 total: 90 min
week 3 total: 165 min
grand total : 390 min
The PREDICT answer: reg[1][1] throws ArrayIndexOutOfBoundsException — week 2 has length 1, so its only index is 0. If you predicted NullPointerException, re-check: row 1 WAS assigned; it's just short.
MARK YOURSELF/100
Jagged declaration via new int[3][]25
Three rows assigned, correct lengths 3·1·425
Loops driven by length — no hard-coded sizes25
Weekly totals + grand total correct (135/90/165/390)15
PREDICT answered correctly before running10

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' / null from the instant new runs.
  • 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.
  • 2Dquiz[row][column], row first. quiz.length = rows, quiz[r].length = that row's columns, quiz[r] is a whole 1D array.
  • JAGGEDnew int[3][] — first dimension compulsory, rows born separately with their own lengths. Krish's register: 3 · 1 · 4. Unassigned row = null.
YOUR FOLDER AFTER THIS ADD-ON — CHECK BEFORE YOU LEAVE
Desktop\java-practice\u1-arrays\
DeclareTour.java <- all 4 declaration spellings
FillTour.java <- defaults + 5 fill ways + for-each
MarksReport.java <- highest 91 · average 78.0
GridTour.java <- 3×4 grid · nested loops
CricketRegister.java <- jagged 3·1·4 · Krish's weeks
MyRegister.java <- YOUR build · totals 135/90/165 · grand 390
*.class <- javac made these
Same root as always. One 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.

OBJECT ORIENTED PROGRAMMING THROUGH JAVA · UNIT-1 ADD-ON · ARRAYSVCE · K TRISHAANK