π§Έ ELI5
A window is like a school desk. Buttons, labels, text fields, and tables are little objects you place on the desk. A layout manager is the teacher saying: "you sit north, you sit center, you sit in rows."
Think of Java as a city of little robots. Classes are robot plans, objects are real robots, files are toy boxes, threads are friends working at the same time, and sockets are phones between computers.
Windows, buttons, tables, layouts, and events.
Open a file safely without pretending it always exists.
Inheritance, static blocks, instance blocks, and order.
Many clients, one server, sockets, ports, streams.
Repeated questions, answer plans, and Java 6 code recipes.
Do not study these chapters as isolated islands. They connect: UI opens files, files throw exceptions, serialization uses files, servers use threads, and sockets use I/O streams.
| Topic | Best reference | 5-year-old idea | Exam danger |
|---|---|---|---|
| UI / AWT / Swing | JEMAI 2021, chapters III-IV | Put buttons and text areas in a window. | Forgetting layouts and event listeners. |
| File / Exceptions | SCJP 2022 VI-2 + JEMAI FileDialog | A File object is a label on a toy box, not the toys. | Thinking new File() creates the real file. |
| OOP / Blocks / GC / String | SCJP 2022 II, III, VI | Plans, robots, cleanup truck, and unchangeable words. | Wrong execution order or assuming String changes itself. |
| JTable / Threads / TCP | JEMAI 2021 IV + VI | Tables show rows; threads serve many children; sockets are phones. | Calling run() instead of start(). |
| Collections / sorting / text parsing | exams 2017, 2018, 2019, 2024 | Put many things in the right bag, then sort or search the bag. | Confusing Collection, Collections, List, Set, and Map. |
| Exam source | Repeated question shape | What your answer must contain |
|---|---|---|
exam24.pdf | Notes.obj, SomeNotes.txt, Moyennes.obj, sorted display | Serializable classes, object streams, exception handling, average formula, descending sort. |
exams.pdf 2019 | Notes.txt to Moyennes.txt, text to object, threads, collections | Colon parsing, variable note count, class average, serialization, join(), synchronized, yield(). |
exams.pdf 2018 | Employee management from emp.txt | Employee class, collection choice, selection by function code, add/delete, equality rule, serialization. |
exams.pdf 2017 | Count words, count fields, sort employees by salary | Line reading, split("\\s+"), split(":", -1), collection + comparator. |
finalize(), applets, and DataInputStream.readLine() are legacy. Learn them to understand the course; do not copy them blindly into modern production code.
try-with-resources unless your teacher explicitly accepts newer Java. The exam templates below use old-compatible syntax.
AWT is the older box of UI toys. Swing is the newer box. Both need containers, components, layouts, and listeners.
A window is like a school desk. Buttons, labels, text fields, and tables are little objects you place on the desk. A layout manager is the teacher saying: "you sit north, you sit center, you sit in rows."
Frame, Panel, Button, TextArea, FileDialog.JFrame, JButton, JTable, JScrollPane.FlowLayout flows like words, BorderLayout has North/South/East/West/Center, GridLayout makes boxes.bOpen, ta.Frame or JFrame.class MyFrameAWT extends Frame {
Panel pNorth = new Panel();
Button bOpen = new Button("Open");
TextArea ta = new TextArea("");
MyFrameAWT() {
pNorth.add(bOpen);
add(pNorth, BorderLayout.NORTH);
add(ta, BorderLayout.CENTER);
bOpen.addActionListener(new MyActionListenerForOpen(this));
setSize(500, 400);
setVisible(true);
}
}
File is a map label, not the treasureThe course describes File as metadata that negotiates with the real file system. Translation: it points to a path and lets you ask questions or start I/O.
new File("notes.txt") does not read the file. It creates a Java object that says "maybe there is a thing called notes.txt here."
exists(): is it really there?length(): how big?delete(): remove it.renameTo(): change its name/path.A stream is a tiny door where bytes or characters pass one by one.
FileInputStream: read bytes.FileReader: read characters.BufferedReader: read more comfortably.PrintWriter: write formatted text.Files are messy. They can be missing, locked, forbidden, or broken. Java forces you to handle checked exceptions.
FileNotFoundException: cannot find/open.IOException: read/write problem.finally: old way to close.File file = new File(nomComplet);
FileInputStream in = null;
try {
in = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
int count = in.read(data);
String text = new String(data, 0, count);
textArea.setText(text);
} catch (FileNotFoundException e) {
System.out.println("The file is missing: " + e);
} catch (IOException e) {
System.out.println("The file was found, but reading failed: " + e);
} finally {
try {
if (in != null) in.close();
} catch (IOException e) {
System.out.println("Cannot close file: " + e);
}
}
catch(IOException) before catch(FileNotFoundException). The big parent exception would catch everything first, and the child catch becomes unreachable.
Inheritance says "a Dog is an Animal." Composition says "a Car has an Engine." Initialization blocks decide what runs before the object is ready.
If class Dog extends Animal, a Dog can reuse Animal behavior. That is an IS-A relationship.
override: child replaces parent method behavior.overload: same method name, different parameter list.final method: cannot be overridden.static method: hidden, not truly overridden.Static blocks run when the class wakes up. Instance blocks run every time you build a new object, before the constructor finishes.
| Thing | When it runs | How often |
|---|---|---|
static { } | Class loading | Once per class |
{ } | Object creation | Every new object |
| Constructor | After instance blocks | Every new object |
class Init {
static { System.out.println("static first"); }
{ System.out.println("instance before constructor"); }
Init() {
System.out.println("constructor");
}
public static void main(String[] args) {
new Init();
new Init();
}
}
static first prints once. Then each new Init() prints the instance block, then the constructor. If you get that wrong, you lose easy exam points.
When no reference can reach an object anymore, the object becomes eligible for garbage collection. Eligible does not mean "deleted now"; it means "the truck may pick it up later."
You built a toy robot. If nobody has its remote anymore, the robot is lost. Java may clean it from memory later.
Robot r = new Robot();
r = null; // no remote points to the robot now
// robot is eligible for GC
finalize()The SCJP PDF mentions finalize() as code that may run before deletion. That is legacy knowledge.
finalize() for closing files or sockets.finalize()", the plan is bad. In Java 6 exam code, close in finally; in modern Java, try-with-resources is cleaner.
String is a word written in stoneThe confusing part is this: methods like concat(), toLowerCase(), and replace() do not edit the same String. They return a new String.
Imagine a word carved on a stone. You cannot erase it. If you want a new word, Java gives you a new stone.
String x = "Java";
x.concat(" Rules!");
System.out.println(x); // Java
x = x.concat(" Rules!");
System.out.println(x); // Java Rules!
When you change text many times, use a mutable builder.
| Class | Mutable? | Thread-safe? | Use when |
|---|---|---|---|
String | No | Yes, because immutable | Normal text |
StringBuilder | Yes | No | Fast local building |
StringBuffer | Yes | Yes | Old synchronized code |
charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toUpperCase(), trim().
An assertion says: "I believe this must be true here." If it is false while testing, Java shouts.
Good assertion: after sorting, the list should be ordered. Bad assertion: checking if the user typed a password. User mistakes need real exceptions or validation, not assertions.
int age = readAgeFromTrustedTestData();
assert age >= 0 : "age cannot be negative";
Assertions are disabled by default, exactly as the SCJP PDF says.
java -ea com.insat.TestClass // enable assertions
java -da com.insat.TestClass // disable assertions
assert. If assertions are off, that behavior disappears.
Imagine taking a photo of your toy with all its current colors and numbers. Later, Java can load the photo and rebuild the toy.
The class must implement Serializable. Then ObjectOutputStream can write the object.
class Employee implements Serializable {
String name;
transient String secret; // not saved
}
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream("employees.ser"));
out.writeObject(new Employee());
} catch (IOException e) {
System.out.println(e);
} finally {
try {
if (out != null) out.close();
} catch (IOException e) {
System.out.println(e);
}
}
ObjectInputStream reads the saved bytes and returns an object. You cast it back to the real type.
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("employees.ser"));
Employee e = (Employee) in.readObject();
} catch (IOException e) {
System.out.println(e);
} catch (ClassNotFoundException e) {
System.out.println(e);
} finally {
try {
if (in != null) in.close();
} catch (IOException e) {
System.out.println(e);
}
}
JTable is a spreadsheet-looking Swing componentThe JEMAI Swing chapter builds a table using a TableModel. The table asks the model: how many rows, how many columns, and what value is at row X column Y?
| Method | Question it answers |
|---|---|
getColumnCount() | How many vertical columns? |
getRowCount() | How many horizontal rows? |
getValueAt(row, col) | What is inside this cell? |
getColumnName(col) | What is the column title? |
getColumnClass(col) | What type of object is in this column? |
TableModel model = new AbstractTableModel() {
public int getColumnCount() { return columnNames.length; }
public int getRowCount() { return rows.length; }
public Object getValueAt(int row, int col) { return rows[row][col]; }
public String getColumnName(int col) { return (String) columnNames[col]; }
public Class getColumnClass(int col) { return getValueAt(0, col).getClass(); }
};
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
frame.getContentPane().add(scrollPane);
JTable shows. TableModel knows. JScrollPane lets you move when the table is bigger than the window.
The SCJP PDF uses regex with Pattern and Matcher. Tokenizing is the general idea of breaking input into smaller tokens.
A regex is a tiny search language. It can find pieces that match a pattern.
Pattern p = Pattern.compile("ab");
Matcher m = p.matcher("abaaaba");
while (m.find()) {
System.out.print(m.start() + " ");
}
// output: 0 4
If input is "Ali;20;INSAT", tokens are Ali, 20, and INSAT.
String line = "Ali;20;INSAT";
String[] tokens = line.split(";");
System.out.println(tokens[0]); // Ali
"." means "any character"; to split on a real dot, use "\\.".
The exams ask collections almost every year. If you cannot choose the right collection and sort it, you are not ready.
| Family | Use it when | Example |
|---|---|---|
List | You keep order and allow duplicates. | ArrayList, LinkedList |
Set | You want unique elements. | HashSet, TreeSet |
Map | You search by key: id to employee, code to list. | HashMap, TreeMap |
Queue | You process first-in-first-out tasks. | LinkedList |
Collection is the root interface for groups like List and Set. Collections is a utility class with static methods like sort(), reverse(), and synchronizedList().
Collection c = new ArrayList(); // broad, old style
List names = new ArrayList(); // ordered bag
Set ids = new HashSet(); // unique bag
Map byId = new HashMap(); // key -> value bag
Use the interface on the left and the concrete class on the right. That is clean design and exam-friendly.
List<Employee> employees = new ArrayList<Employee>();
Set<Integer> uniqueIds = new HashSet<Integer>();
Map<Integer, Employee> employeeById = new HashMap<Integer, Employee>();
employees.add(new Employee(1, "Ali", "BEN ALI", 2, "Dev"));
Employee e = employeeById.get(new Integer(1));
When the question says "tri croissant selon salaire" or "tri dΓ©croissant des moyennes", use Collections.sort with a Comparator.
// Ascending salary
Collections.sort(employees, new Comparator<Employee>() {
public int compare(Employee a, Employee b) {
return a.salaire - b.salaire;
}
});
// Descending average
Collections.sort(averages, new Comparator<StudentAverage>() {
public int compare(StudentAverage a, StudentAverage b) {
return Double.compare(b.moyenne, a.moyenne);
}
});
java.awt.* and java.util.*, the name List becomes ambiguous because AWT also has java.awt.List. In exam code, write java.util.List or avoid wildcard UI imports.
The TCP server in the 2021 PDF uses Server extends Thread and Connection extends Thread so the server can keep listening while clients are handled.
This is non-negotiable: call start() to create a new worker. Calling run() is just a normal method call on the same worker.
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println("work");
}
});
t.start(); // correct: new thread
t.run(); // not parallel: just calls the method
If two workers touch the same toy box at the same time, they can make a mess. That is a race condition. Use synchronization or better design.
synchronized protects one critical section.StringBuffer is synchronized; StringBuilder is not.TCP gives a reliable conversation: connect, talk, close. UDP is faster but not guaranteed. The course focuses on Java sockets: Socket for the client, ServerSocket for the server.
Socket(host, port).ServerSocket(port).accept() to wait for a client.// Client idea
Socket s = null;
try {
s = new Socket(host, 6061);
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("Bonjour");
System.out.println(in.readLine());
} finally {
if (s != null) s.close();
}
// Server idea
ServerSocket server = new ServerSocket(6061);
while (true) {
final Socket client = server.accept();
new Thread(new Runnable() {
public void run() {
handle(client);
}
}).start();
}
No resume can magically guarantee zero faults if you do not practice. But the old exams repeat the same patterns. Master these templates and you cover the real danger zone.
StudentNote, StudentAverage, or Employee.BufferedReader/PrintWriter; object file needs ObjectInputStream/ObjectOutputStream.":", trim fields, convert numbers with Integer.parseInt or Double.parseDouble.ArrayList because order, duplicates, sorting, add/delete are needed.import java.io.*; and import java.util.*;. If you also use AWT, avoid import java.awt.*; with java.util.* unless you qualify java.util.List.
Use this when the question says Notes.obj, DS, Examen, and Moyennes.obj.
class StudentNote implements Serializable {
int id;
String nom;
String prenom;
double ds;
double examen;
StudentNote(int id, String nom, String prenom, double ds, double examen) {
this.id = id;
this.nom = nom;
this.prenom = prenom;
this.ds = ds;
this.examen = examen;
}
double moyenne() {
return ds * 0.3 + examen * 0.7;
}
}
class StudentAverage implements Serializable {
int id;
String nom;
String prenom;
double moyenne;
StudentAverage(StudentNote n) {
id = n.id;
nom = n.nom;
prenom = n.prenom;
moyenne = n.moyenne();
}
}
2017 and 2018 both ask employee files and sorting/filtering. Equality by function code is strange, but the 2018 exam explicitly asks it.
class Employee implements Serializable {
int id;
String nom;
String prenom;
int codeFonction;
String fonction;
int salaire;
public boolean equals(Object o) {
if (!(o instanceof Employee)) return false;
Employee e = (Employee) o;
return codeFonction == e.codeFonction;
}
public int hashCode() {
return codeFonction;
}
}
Use this for CalculMoyenne.java, word counting, field counting, and colon-separated employee files.
public class CalculMoyenne {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java CalculMoyenne Notes.txt Moyennes.txt");
return;
}
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new FileReader(args[0]));
pw = new PrintWriter(new FileWriter(args[1]));
String line;
double classSum = 0;
int studentCount = 0;
while ((line = br.readLine()) != null) {
String[] p = line.split(":");
double sum = 0;
int noteCount = 0;
for (int i = 2; i < p.length; i++) {
sum += Double.parseDouble(p[i].trim());
noteCount++;
}
double avg = sum / noteCount;
pw.println(line + ":" + avg);
classSum += avg;
studentCount++;
}
pw.println("Moyenne Generale : " + (classSum / studentCount));
} catch (Exception e) {
System.out.println("Erreur: " + e);
} finally {
try { if (br != null) br.close(); } catch (IOException e) {}
if (pw != null) pw.close();
}
}
}
line.trim().split("\\s+").length, but if the trimmed line is empty, answer is 0. Count fields separated by :: use line.split(":", -1).length to keep empty fields.
The safest exam design is: read the whole List, modify it, then rewrite the whole object file. Blindly appending objects with a new ObjectOutputStream can corrupt the stream header.
static List<StudentNote> loadNotes(String file)
throws IOException, ClassNotFoundException {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(file));
return (List<StudentNote>) in.readObject();
} finally {
if (in != null) in.close();
}
}
static void saveNotes(String file, List<StudentNote> notes)
throws IOException {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(notes);
} finally {
if (out != null) out.close();
}
}
List<StudentNote> notes = loadNotes("Notes.obj");
BufferedReader br = new BufferedReader(new FileReader("SomeNotes.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] p = line.split(":");
notes.add(new StudentNote(
Integer.parseInt(p[0].trim()),
p[1].trim(),
p[2].trim(),
Double.parseDouble(p[3].trim()),
Double.parseDouble(p[4].trim())
));
}
br.close();
saveNotes("Notes.obj", notes);
List<StudentNote> notes = loadNotes("Notes.obj");
List<StudentAverage> avgs = new ArrayList<StudentAverage>();
for (int i = 0; i < notes.size(); i++) {
avgs.add(new StudentAverage(notes.get(i)));
}
Collections.sort(avgs, new Comparator<StudentAverage>() {
public int compare(StudentAverage a, StudentAverage b) {
return Double.compare(b.moyenne, a.moyenne);
}
});
// then write avgs to Moyennes.obj or print them
Use one ArrayList<Employee> for normal management. Use HashMap<Integer, Employee> only when the question emphasizes fast lookup by id.
List<Employee> employees = new ArrayList<Employee>();
// select by function code
for (int i = 0; i < employees.size(); i++) {
Employee e = employees.get(i);
if (e.codeFonction == 2) {
System.out.println(e.nom + " " + e.prenom);
}
}
// delete by id
Iterator<Employee> it = employees.iterator();
while (it.hasNext()) {
Employee e = it.next();
if (e.id == 80800) {
it.remove();
}
}
// sort salary ascending
Collections.sort(employees, new Comparator<Employee>() {
public int compare(Employee a, Employee b) {
return a.salaire - b.salaire;
}
});
2019 asks creation possibilities, join(), synchronized, yield(), and creating N threads that call displayMsg() ten times.
class Worker extends Thread {
public void run() {
displayMsg();
}
static synchronized void displayMsg() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " message " + i);
Thread.yield();
}
}
}
public class LaunchThreads {
public static void main(String[] args) throws Exception {
int n = Integer.parseInt(args[0]);
Thread[] threads = new Thread[n];
for (int i = 0; i < n; i++) {
threads[i] = new Worker();
threads[i].start();
}
for (int i = 0; i < n; i++) {
threads[i].join();
}
}
}
| Question | Perfect short answer |
|---|---|
| Serialization | Mechanism that converts an object graph into bytes to save or transmit it. Class implements Serializable; use ObjectOutputStream and ObjectInputStream; transient fields are skipped. |
| Garbage Collection | Automatic memory cleanup for unreachable objects. Trigger is not guaranteed. Programmer can remove references, call System.gc() as a request, and use finalize() only as legacy course knowledge. |
| Static block vs instance block | Static block runs once when the class is loaded. Instance block runs before the constructor every time an object is created. |
protected | Accessible in the same package and in subclasses, including subclasses in another package through inheritance. |
static | Belongs to the class, not to one object. Shared by all instances. |
final | Variable cannot be reassigned, method cannot be overridden, class cannot be subclassed. |
synchronized | Locks a method/block so only one thread enters that critical section for the same monitor. |
Runnable vs Thread | Runnable is the task contract with run(). Thread is the worker that can execute a task with start(). |
join() | Current thread waits until another thread finishes. |
yield() | Current thread politely suggests giving another ready thread a chance. It is not guaranteed. |
Collection vs Collections | Collection is an interface; Collections is a utility class with static helper methods. |
These are the mistakes that cost points. If one sounds unfamiliar, go back to its section.
Does String x = "A"; x.concat("B"); change x?
No. Strings are immutable. Without assignment, x is still "A".
Does new File("a.txt") create a.txt on disk?
No. It creates a Java path object. Real creation happens through writing or explicit creation methods.
Which runs once: static block or instance block?
Static block runs once when the class loads. Instance block runs for every object.
In networking, who uses ServerSocket?
The server. The client uses Socket.
What is the difference between Collection and Collections?
Collection is an interface. Collections is a utility class with static methods like sort().
How do you safely add notes from text into Notes.obj?
Read the serialized List, parse SomeNotes.txt, add objects to the list, then rewrite the whole object file.
File describes a path; streams read/write content.finalize().StringBuilder for many edits.Serializable; streams save/restore.ArrayList for sortable lists, HashSet for uniqueness, HashMap for lookup by key.start() creates concurrent work; run() alone does not.accept(); client connects with Socket.1-2-3-4-5-6-ALL-Java-JEMAI-2021.pdf for AWT, Swing, JTable, TCP/IP, and threaded server examples; CoursJemaiSCJP_Full2022.pdf for inheritance, initialization blocks, garbage collection, exceptions, assertions, strings, I/O, serialization, parsing, and tokenizing; exam24.pdf and exams.pdf for repeated exam patterns from 2017, 2018, 2019, and 2024.