Commit d985518
committed
feat: Implement auto-generated student roll numbers using static counter and date-based prefix
WHAT the code does:
- Defines StudentName class:
- Private field rollNo stores the unique identifier for each student.
- Static counter count starts at 1 and increments with each new object.
- Private method assignRollNo():
- Uses java.util.Date to fetch the current year.
- Constructs roll number as "University-<year>-<count>".
- Increments count for the next student.
- Constructor assigns rollNo by calling assignRollNo().
- Public getter getRollNo() returns the roll number.
- Defines main class ToughStaticSolveIt:
- Creates three StudentName objects (s1, s2, s3).
- Prints their generated roll numbers.
WHY this matters:
- Demonstrates **static variable usage** for generating unique sequential identifiers shared across all instances.
- Shows how to combine static state with dynamic data (current year from Date) to generate meaningful roll numbers.
- Ensures each student object gets a unique roll number without requiring manual input.
HOW it works:
1. First StudentName object:
- count = 1 → assigns "University-2025-1".
- count increments to 2.
2. Second StudentName object:
- count = 2 → assigns "University-2025-2".
- count increments to 3.
3. Third StudentName object:
- count = 3 → assigns "University-2025-3".
- count increments to 4.
4. Printing confirms unique sequential roll numbers.
Tips and gotchas:
- java.util.Date.getYear() is deprecated; prefer java.time.LocalDate.now().getYear() for modern code.
- Static counter resets only when JVM restarts; persistence across sessions would require external storage (file, database).
- Class and method naming could follow Java conventions:
- StudentName → Student
- ToughStaticSolveIt → RollNumberGeneratorDemo
- Making assignRollNo() private ensures roll numbers are controlled internally, enforcing encapsulation.
Use-cases / analogies:
- Similar to how universities or organizations auto-generate IDs for students, employees, or tickets.
- Like a bakery numbering receipts: each new customer gets the next number, prefixed with the current year.
Short key: java static-counter unique-id auto-generated roll-numbers encapsulation.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 8aeaf36 commit d985518
2 files changed
+7
-23
lines changedThis file was deleted.
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
5 | 4 | | |
6 | 5 | | |
7 | 6 | | |
8 | 7 | | |
9 | | - | |
10 | | - | |
| 8 | + | |
11 | 9 | | |
12 | 10 | | |
13 | 11 | | |
14 | 12 | | |
15 | 13 | | |
16 | 14 | | |
17 | | - | |
18 | | - | |
| 15 | + | |
| 16 | + | |
19 | 17 | | |
20 | 18 | | |
21 | | - | |
22 | | - | |
| 19 | + | |
| 20 | + | |
23 | 21 | | |
24 | 22 | | |
25 | 23 | | |
| |||
34 | 32 | | |
35 | 33 | | |
36 | 34 | | |
37 | | - | |
| 35 | + | |
0 commit comments