⚡ TechVani: AI, Technology, Apps, Coding & Digital World
TechVaniAI • Technology • Apps • Coding • Digital World
HomeAI & TechAppsCodingFree AI ToolsStudent TechSecurityAboutContactPrivacy
TECHVANI // LEARN. BUILD. TEST.

Learn the tech. Build the idea.

Clear study notes, tested lab files and practical guides for coding, AI and digital safety.

Explore Latest →
šŸ¤– AI & TechAI news, tools & guides šŸ“± Apps & ToolsUseful apps & websites šŸ’» CodingProgramming & web development šŸŽ“ Student TechStudy & career technology šŸ” Cyber SecuritySafety & awareness

Latest Posts

Circuit Notebook theme

Exam Notes

šŸ“š BTech CSE Exam Notes

Find Semester 1-8 subjects in one place. Choose a semester and open the notes you need. This is a general study guide, not an official syllabus.

Open Exam Notes →🧪 Open Lab Files →

Exam Numericals & Study Series

Practice CPU scheduling and explore OS and DBMS topics in separate, easy-to-follow parts. New topics will appear in the hub as they are published.

Open Numericals Hub →

Start here and stay in touch

New to TechVani? Start with our free AI tools guide for students. It covers which tools to try and what to check before relying on an answer.

For step-by-step videos, visit SiteSudhar on YouTube.

Join TechVani on WhatsApp

Get new AI tools and coding guides in your WhatsApp Updates tab.

Browse Topics

Popular Posts

TechVani

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.

Run each whole block separately: save it as 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

  1. Source, bytecode and JVM
  2. JDK, versions and commands
  3. Primitive and reference types
  4. Arithmetic and numeric limits
  5. Strings and logical equality
  6. Branches and loops
  7. Methods and pass-by-value
  8. Arrays and copying
  9. Classes and object state
  10. Constructors and initialization
  11. Encapsulation and invariants
  12. Access, packages and imports
  13. this, static and final
  14. Composition and inheritance
  15. Overload and override
  16. Abstract classes and interfaces
  17. Runtime dispatch and casts
  18. Object equality and hashCode
  19. Collections: List, Set and Map
  20. Generics and type safety
  21. Iterators and safe changes
  22. Exception categories
  23. Try, catch and finally
  24. Try-with-resources
  25. Input parsing and validation
  26. Files and persistence
  27. Exact decimal arithmetic
  28. Threads and synchronization
  29. Library worked flow
  30. Testing and boundaries
  31. Documentation and source credit
  32. 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.

Worked example: Demo.java compiles into Demo.class; run the class name rather than the filename.
Exam question: Does bytecode guarantee identical behavior on every platform?
Answer: No. File paths, encodings, native code and environment can differ.
Demo.java sourceCompiler: Demo.class bytecodeCompatible JVM loads and runs
Source-to-runtime flow. Compile target, libraries and environment must match the execution setup.

2. JDK, versions and commands

The JDK supplies development tools; a runtime supplies execution services. These complete demos target Java11, avoiding later language features.

Worked example: javac --release 11 -Xlint:all Demo.java then java Demo.
Exam question: Can a Java11 JVM run arbitrary newer class files?
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.

Worked example: int3 and Integer3 differ in primitive/reference behavior, boxing and nullability.
Exam question: Is String primitive?
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.

Worked example: 7/2 is3; -7/2 is-3; Math.addExact rejects int overflow.
Exam question: Does Java int overflow throw automatically?
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.

Worked example: Two separately constructed equal Strings have equal contents without being the same object.
Exam question: Can == be used to compare intended text contents reliably?
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.

Worked example: An empty array must produce count0 without accessing index0.
Exam question: What prevents an infinite while loop?
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.

Worked example: A method can change array[0]; assigning its parameter a new array does not rebind the caller variable.
Exam question: Is Java pass-by-reference?
Answer: No.
Caller values points to arrayParameter receives a reference copyMutation shared; reassignment local
The method and caller can initially refer to the same array. Changing one element is visible; rebinding the local parameter is not.

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.

Worked example: Copy int[] with clone for independent primitive elements; nested arrays need a deliberate depth policy.
Exam question: Does arr2=arr1 copy elements?
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.

Worked example: Book holds a positive inventory ID and nonblank title.
Exam question: Does creating an object create a new class definition?
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.

Worked example: Book(-1,title) throws rather than returning a usable invalid book.
Exam question: Is a constructor an ordinary return-value method?
Answer: No.

11. Encapsulation and invariants

Private fields restrict access; controlled operations must maintain invariants. Getters returning mutable internals can still leak control.

Worked example: Borrow refuses an already-issued one-copy Book; return refuses an already-available one.
Exam question: Do private fields alone prove valid state?
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.

Worked example: Put related classes in a named package and compile with the matching directory layout.
Exam question: Are package access and protected identical?
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.

Worked example: A final List reference can still refer to a mutable list that accepts add.
Exam question: Does final imply deep immutability?
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.

Worked example: Library has a Map of Books; it is not a Book.
Exam question: Does single class inheritance prevent 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.

Worked example: send(String) and send(int) overload; ConsoleNotifier overrides send(String).
Exam question: Can return type alone distinguish ordinary overloads?
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.

Worked example: Notifier has send; two concrete implementations supply behavior.
Exam question: Are interfaces required to be method-body-free in modern Java?
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.

Worked example: Notifier n=new ConsoleNotifier(); n.send reaches ConsoleNotifier.
Exam question: Does casting change the object's real class?
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.

Worked example: Two BookKey values with ID7 compare equal and collapse to one HashSet entry.
Exam question: Should keys change equality fields while stored in a hash map?
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.

Worked example: LinkedHashMap preserves insertion order for the demo catalog; HashMap does not promise that order.
Exam question: Does every Set preserve insertion order?
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.

Worked example: List<Integer> is not a subtype of List<Number>; List<? extends Number> can read Number values.
Exam question: Can generics accept int as a type argument?
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.

Worked example: Iterate with Iterator and remove selected elements via its remove when supported.
Exam question: Can ConcurrentModificationException be used as a synchronization plan?
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.

Worked example: Invalid model arguments can use IllegalArgumentException; IOException needs a clear handling/propagation policy.
Exam question: Is every Exception checked?
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.

Worked example: A failing read should not be followed by a misleading success message.
Exam question: Should an empty catch block hide an operation failure?
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.

Worked example: Acquire A then B; close B then A, even after body failure.
Exam question: Does try-with-resources close every unrelated object in scope?
Answer: No. It closes declared resources.
Acquire A, then acquire BBody fails: primary exceptionClose B then A: suppressed failures
Completed resources close in reverse order; suppressed exceptions remain available on the primary failure.

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.

Worked example: A mark must be an integer from0to100; 40 passes,39fails,101 rejects.
Exam question: Does successful parse mean valid input?
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.

Worked example: Use UTF-8 and a disposable temporary directory for any extension.
Exam question: Does a successful UI check make persistent checkout atomic?
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.

Worked example: 0.10 plus0.20 gives0.30; 1.0 and1.00 compare numerically equal but are not equals.
Exam question: Why avoid new BigDecimal(0.1) for intended decimal0.1?
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.

Worked example: Concurrent check-then-issue must be one protected storage operation.
Exam question: Is a collection reference being final enough for thread safety?
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.

Worked example: Add1, issue1 true, issue1 false, return1 true, return1 false.
Exam question: Is this complete production checkout software?
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.

Worked example: Check negative ID, blank title, missing copy and repeated issue/return, as well as success.
Exam question: Is one passing sample a proof?
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.

Worked example: Run each whole program independently and record its exact result.
Exam question: What makes a demo portable to another learner?
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.

Worked example: State Java11, class name, arguments, expected output and invalid-input policy in an exam program answer.
Exam question: What should be checked against the assigned handout?
Answer: Required topics, compiler/language version and assessment rules.

Concept comparison

ConceptRuleAvoid
== referencesIdentityAssuming text equality
equals/hashCodeEqual objects share hash codeMutable equality fields in keys
OverloadApplicable compile-time signatureReturn-type-only overload
OverrideRuntime instance behaviorAssuming fields/static methods dispatch
final referenceCannot be reboundAssuming referenced object immutable
GenericsCompile-time element constraintsRaw types and unchecked mixing
Try-with-resourcesReverse close, suppressionSwallowed failures
synchronizedGuard matched shared accessesUnguarded check-then-act

Checked output and boundary reference

ExampleResultContract
Reference change and clonecaller9;copy7int[] clone independent
Stringsidentityfalse,equaltrueSeparately constructed String values
Libraryissuetrue,false;returntrue,falseOne physical copy per ID
HashSet keys1 distinct keyEqual immutable ID7
Resource failureB then A closesBody primary; B,A suppressed
Marks39FAIL,40PASS,100PASS101,junk,negative invalid
Decimals0.30;third0.33Text construction;HALF_UP2places
BigDecimal scaleequalsfalse,compareTo01.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.

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