Java Programming | Semester 4 Core Notes
Semester4 - Page1: Java Programming. 32 numbered topics, highlighted rules, worked examples, answered exam questions, three diagrams, two tables and five complete Java11 programs. General common-core guide, not an official assessed syllabus or past-paper prediction. Check your assigned outline and language version.
Demo.java, compile with javac --release 11 -Xlint:all Demo.java, then run java Demo. Use a JDK with Java11 support. Examples tested on OpenJDK11.0.30. Do not paste multiple public Demo classes into one file. Inputs are fixed teaching examples, not interactive production programs. The library models one physical copy per inventory ID, without member rules, persistence or concurrency. The resource block deliberately throws close failures to show suppression; it does not open real files. Mark parser accepts ASCII digits only,0to100; no signs, spaces or decimal point. All programs use standard libraries and write no personal files.Topic map
- Source, bytecode and JVM
- JDK, versions and commands
- Primitive and reference types
- Arithmetic and numeric limits
- Strings and logical equality
- Branches and loops
- Methods and pass-by-value
- Arrays and copying
- Classes and object state
- Constructors and initialization
- Encapsulation and invariants
- Access, packages and imports
- this, static and final
- Composition and inheritance
- Overload and override
- Abstract classes and interfaces
- Runtime dispatch and casts
- Object equality and hashCode
- Collections: List, Set and Map
- Generics and type safety
- Iterators and safe changes
- Exception categories
- Try, catch and finally
- Try-with-resources
- Input parsing and validation
- Files and persistence
- Exact decimal arithmetic
- Threads and synchronization
- Library worked flow
- Testing and boundaries
- Documentation and source credit
- Revision and common-core limits
1. Source, bytecode and JVM
Java source compiles to class files that a compatible JVM loads and executes. Portability still depends on library versions and external assumptions.
Answer: No. File paths, encodings, native code and environment can differ.
2. JDK, versions and commands
The JDK supplies development tools; a runtime supplies execution services. These complete demos target Java11, avoiding later language features.
Answer: No. Compile for the target and check its dependencies.
3. Primitive and reference types
Primitives carry values; references identify objects or arrays and may be null. String is an immutable reference type.
Answer: No.
4. Arithmetic and numeric limits
Integer division truncates toward zero. int and long arithmetic can overflow; use checked operations or a suitable exact type when required.
Answer: Ordinary addition wraps; addExact detects overflow.
5. Strings and logical equality
Use equals for String contents and == for reference identity. String immutability does not make a variable holding a String unassignable.
Answer: No. Use an equality contract and handle null.
6. Branches and loops
Conditions are Boolean. Trace termination, bounds and invalid input; enhanced-for is not a general safe structural-removal mechanism.
Answer: A terminating condition and progress on every continuing path.
7. Methods and pass-by-value
All arguments are passed by value, including the value of an object reference. Mutating an object differs from reassigning a local parameter.
Answer: No.
Pass-by-value, arrays and String equality
public class Demo {
static void change(int[] values) {
values[0] = 9;
values = new int[] {99};
}
public static void main(String[] args) {
int[] values = {1};
change(values);
int[] copy = values.clone(); copy[0] = 7;
String a = new String("Java"), b = new String("Java");
System.out.println("caller: " + values[0] + "; copy: " + copy[0]);
System.out.println("identity: " + (a == b) + "; equal: " + a.equals(b));
System.out.println("division: " + 7/2 + "; negative: " + (-7/2));
}
}
Checked output:
caller: 9; copy: 7 identity: false; equal: true division: 3; negative: -3
8. Arrays and copying
Arrays have fixed length and zero-based bounds. Assignment aliases an array; cloning a reference array copies element references, not the nested objects.
Answer: No. Both references identify the same array.
9. Classes and object state
A class defines members; each instance has its own instance state. Design valid states before exposing operations.
Answer: No. It creates an instance of the class.
10. Constructors and initialization
Constructors initialize instances and have no return type. Validate arguments and initialize fields before publishing a usable object.
Answer: No.
11. Encapsulation and invariants
Private fields restrict access; controlled operations must maintain invariants. Getters returning mutable internals can still leak control.
Answer: No. Every public path must uphold the contract.
12. Access, packages and imports
Access rules distinguish public, protected, package access and private. Packages organize names; an import is not a runtime copy of a class.
Answer: No. Protected adds subclass-related access rules with limits.
13. this, static and final
this names the current instance; static members have no implicit instance. final prevents reassignment/overriding/extension as applicable, not every mutation of referenced data.
Answer: No.
14. Composition and inheritance
Composition is has-a; class inheritance should preserve the base contract. Java classes have one direct superclass but may implement multiple interfaces.
Answer: No.
15. Overload and override
Overloading selects applicable signatures using compile-time information. Overriding supplies runtime behavior for an inherited instance method; use @Override.
Answer: No.
16. Abstract classes and interfaces
Abstract classes cannot be instantiated directly. Interfaces state contracts and may include supported default/static methods; ordinary interface fields are public static final.
Answer: No. Version-specific default/static/private method rules exist.
17. Runtime dispatch and casts
Virtual instance calls use the object's runtime implementation. Downcasts need a valid runtime type; fields and static methods do not dispatch like overridden instance methods.
Answer: No.
18. Object equality and hashCode
Equals should be reflexive, symmetric, transitive and consistent, with null unequal. Equal objects must have equal hash codes; unequal objects can collide.
Answer: No. Lookup behavior can break.
Equality keys, generics and interface dispatch
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
public class Demo {
static final class BookKey {
private final int id;
BookKey(int id) { if (id <= 0) throw new IllegalArgumentException("ID"); this.id = id; }
@Override public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof BookKey)) return false;
return id == ((BookKey) other).id;
}
@Override public int hashCode() { return Objects.hash(id); }
}
interface Notifier { String send(String text); }
static final class ConsoleNotifier implements Notifier {
@Override public String send(String text) { return "console: " + text; }
}
static int total(List<Integer> values) {
int sum = 0;
for (int value : values) sum = Math.addExact(sum, value);
return sum;
}
public static void main(String[] args) {
Set<BookKey> keys = new HashSet<>(); keys.add(new BookKey(7)); keys.add(new BookKey(7));
System.out.println("distinct keys: " + keys.size());
Notifier n = new ConsoleNotifier(); System.out.println(n.send("loan ready"));
System.out.println("total: " + total(List.of(2,3,4)));
}
}
Checked output:
distinct keys: 1 console: loan ready total: 9
19. Collections: List, Set and Map
List keeps an indexed sequence, Set models distinct elements and Map binds unique keys to values. Null and ordering policies depend on implementation.
Answer: No.
20. Generics and type safety
Generics constrain element types at compile time. Avoid raw types; generic types are invariant and primitives need wrapper types as type arguments.
Answer: No. Use Integer or a different representation.
21. Iterators and safe changes
Use supported iterator removal where available; avoid structural modification through an unrelated path during iteration. Fail-fast exceptions are not concurrency correctness.
Answer: No.
22. Exception categories
Checked exceptions need handling or declaration except where language rules exempt them. RuntimeException and Error subclasses are unchecked; catch meaningful failures, not every Throwable.
Answer: No. RuntimeException subclasses are unchecked.
23. Try, catch and finally
Catch specific failures and preserve context. A finally block usually runs on exit from the try, but JVM termination is not an ordinary control-flow exit.
Answer: No.
24. Try-with-resources
Resources implementing AutoCloseable close in reverse declaration order. If body and close both fail, the body exception is primary and close failures are suppressed.
Answer: No. It closes declared resources.
Reverse close order and suppressed exceptions
import java.io.IOException;
public class Demo {
static final class Resource implements AutoCloseable {
private final String name;
Resource(String name) { this.name = name; System.out.println("acquire " + name); }
@Override public void close() throws IOException {
System.out.println("close " + name);
throw new IOException("close " + name);
}
void use() { System.out.println("use " + name); }
}
public static void main(String[] args) {
try (Resource a = new Resource("A"); Resource b = new Resource("B")) {
a.use(); b.use(); throw new IOException("body");
} catch (IOException ex) {
System.out.println("primary: " + ex.getMessage());
for (Throwable s : ex.getSuppressed()) System.out.println("suppressed: " + s.getMessage());
}
}
}
Checked output:
acquire A acquire B use A use B close B close A primary: body suppressed: close B suppressed: close A
25. Input parsing and validation
Parsing checks representation; validation checks domain rules. Handle null/blank and reject out-of-range values separately from number-format errors.
Answer: No.
26. Files and persistence
Choose encoding and close resources; report open/read/write failures. Temporary examples avoid overwriting personal files; successful buffered writes do not promise power-loss durability.
Answer: No. Enforce the rule at the storage boundary.
27. Exact decimal arithmetic
Use BigDecimal from decimal text for exact decimal amounts and choose rounding explicitly. equals includes scale while compareTo compares numerical ordering.
Answer: It represents the binary floating-point value rather than that decimal text exactly.
Strict marks and exact decimal amounts
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Demo {
static int mark(String text) {
if (text == null || !text.matches("[0-9]+")) throw new IllegalArgumentException("digits required");
int value;
try { value = Integer.parseInt(text); }
catch (NumberFormatException ex) { throw new IllegalArgumentException("mark range", ex); }
if (value > 100) throw new IllegalArgumentException("mark range");
return value;
}
public static void main(String[] args) {
for (String text : new String[] {"39","40","100","101","40abc","-1"}) {
try { System.out.println(text + ": " + (mark(text) >= 40 ? "PASS" : "FAIL")); }
catch (IllegalArgumentException ex) { System.out.println(text + ": INVALID"); }
}
BigDecimal sum = new BigDecimal("0.10").add(new BigDecimal("0.20"));
System.out.println("sum: " + sum.toPlainString());
System.out.println("third: " + BigDecimal.ONE.divide(new BigDecimal("3"),2,RoundingMode.HALF_UP));
BigDecimal a = new BigDecimal("1.0"), b = new BigDecimal("1.00");
System.out.println("equals: " + a.equals(b) + "; numeric equal: " + (a.compareTo(b) == 0));
}
}
Checked output:
39: FAIL 40: PASS 100: PASS 101: INVALID 40abc: INVALID -1: INVALID sum: 0.30 third: 0.33 equals: false; numeric equal: true
28. Threads and synchronization
Shared mutable state needs a concurrency policy. synchronized can provide mutual exclusion/visibility for the guarded accesses; it does not make an entire unguarded design safe.
Answer: No.
29. Library worked flow
Validate IDs/title, reject duplicate inventory copies, issue only available copies and return only issued copies. This demo has one physical copy per ID and no member/persistence layer.
Answer: No. Authentication, member rules, persistence and concurrency are separate.
Validated one-copy library catalog
import java.util.LinkedHashMap;
import java.util.Map;
public class Demo {
static final class Book {
private final int id;
private final String title;
private boolean available = true;
Book(int id, String title) {
if (id <= 0 || title == null || title.isBlank())
throw new IllegalArgumentException("positive ID and nonblank title required");
this.id = id; this.title = title.strip();
}
int id() { return id; }
String title() { return title; }
boolean issue() {
if (!available) return false;
available = false; return true;
}
boolean giveBack() {
if (available) return false;
available = true; return true;
}
}
static final class Library {
private final Map<Integer,Book> books = new LinkedHashMap<>();
boolean add(int id, String title) {
Book book = new Book(id, title);
return books.putIfAbsent(book.id(), book) == null;
}
boolean issue(int id) { Book b = books.get(id); return b != null && b.issue(); }
boolean giveBack(int id) { Book b = books.get(id); return b != null && b.giveBack(); }
String title(int id) { Book b = books.get(id); return b == null ? "missing" : b.title(); }
}
public static void main(String[] args) {
Library lib = new Library();
System.out.println("add: " + lib.add(1," DS ") + "; duplicate: " + lib.add(1,"Other"));
System.out.println("title: " + lib.title(1));
System.out.println("issue: " + lib.issue(1) + " " + lib.issue(1));
System.out.println("return: " + lib.giveBack(1) + " " + lib.giveBack(1));
System.out.println("missing: " + lib.issue(99));
try { lib.add(-1,"X"); }
catch (IllegalArgumentException ex) { System.out.println("invalid rejected"); }
}
}
Checked output:
add: true; duplicate: false title: DS issue: true false return: true false missing: false invalid rejected
30. Testing and boundaries
Test empty, normal, boundary, invalid and state-transition paths. Tests can reveal errors but do not replace a contract argument.
Answer: No.
31. Documentation and source credit
A reproducible README records version, compile/run commands, input contract, actual output, limitations and sources. Do not submit fabricated logs.
Answer: Complete source and tested setup with stated requirements.
32. Revision and common-core limits
Separate identity/equality, overload/override, values/references and ownership/resource lifetime. This guide is not an official assessed syllabus.
Answer: Required topics, compiler/language version and assessment rules.
Concept comparison
| Concept | Rule | Avoid |
|---|---|---|
| == references | Identity | Assuming text equality |
| equals/hashCode | Equal objects share hash code | Mutable equality fields in keys |
| Overload | Applicable compile-time signature | Return-type-only overload |
| Override | Runtime instance behavior | Assuming fields/static methods dispatch |
| final reference | Cannot be rebound | Assuming referenced object immutable |
| Generics | Compile-time element constraints | Raw types and unchecked mixing |
| Try-with-resources | Reverse close, suppression | Swallowed failures |
| synchronized | Guard matched shared accesses | Unguarded check-then-act |
Checked output and boundary reference
| Example | Result | Contract |
|---|---|---|
| Reference change and clone | caller9;copy7 | int[] clone independent |
| Strings | identityfalse,equaltrue | Separately constructed String values |
| Library | issuetrue,false;returntrue,false | One physical copy per ID |
| HashSet keys | 1 distinct key | Equal immutable ID7 |
| Resource failure | B then A closes | Body primary; B,A suppressed |
| Marks | 39FAIL,40PASS,100PASS | 101,junk,negative invalid |
| Decimals | 0.30;third0.33 | Text construction;HALF_UP2places |
| BigDecimal scale | equalsfalse,compareTo0 | 1.0 versus1.00 |
Revision and practice resources
For each answer, state the Java version, type/null contract, failure policy and expected output. Keep parsing, domain state and storage separate. Check the boundary and exception paths, not only the successful trace.
- Dev.java learning path
- Oracle Java tutorials
- Back to semester-wise notes
- Java Programming Lab File
- Lab Files index
- Online Compiler
Use Java in the Online Compiler; the Java Lab File contains separate practice programs. Oracle legacy tutorials were written for JDK8; use their core rules with version awareness, and consult Dev.java/current specifications for later features.
Sources
Specification and official language/library references support the rules. Explanations, complete demos and diagrams here are original teaching material. These examples do not require post-Java11 features.
Comments
Post a Comment