Top Banner Ad
BCS403 · 1-Page Cheat Sheet

Object Oriented Programming with Java

BCS403 · YEAR 2 · SEM 4

Object Oriented Programming with Java — Last-Night Cheat Sheet

prephora.in

Five units cover Java/OOP fundamentals, exception handling and I/O/threads, modern Java features, collections, and Spring/Spring Boot basics. Each unit keeps its own API, syntax rule, or framework mechanism.

1. Introduction

Recall anchor. Java: write once, run anywhere through JVM bytecode. OOP models software as classes/objects with encapsulation, inheritance, polymorphism, and abstraction.

Scored points.

  • JVM executes bytecode, JRE provides runtime libraries + JVM, and JDK provides development tools (javac, jar, debugger) + JRE.
  • Java source structure: package declaration (optional), imports, class/interface/enum definitions; file name must match public class name.
  • Core OOP: class is blueprint, object is instance; encapsulation hides data via access modifiers; inheritance reuses/extends behavior; polymorphism allows one interface/multiple forms.
  • Overloading is compile-time (same name, different parameter list); overriding is runtime (same signature in subclass, dynamic dispatch).
  • Abstract class can have state and abstract/concrete methods; interface defines capability contract; since Java 8 interfaces can have default/static methods.
  • Packages organize classes and control access; CLASSPATH/module path locate classes; JAR packages compiled classes/resources for reuse.

Formula strip.

JDK=JRE+Dev tools,JRE=JVM+Libraries,.java→javac.class→JVMrun\text{JDK}=\text{JRE}+\text{Dev tools},\quad \text{JRE}=\text{JVM}+\text{Libraries},\quad \texttt{.java}\xrightarrow{javac}\texttt{.class}\xrightarrow{JVM}\text{run}

Micro-example. class A { void show(int x){} } class B extends A { @Override void show(int x){} } — overriding gives runtime dispatch; adding show(int x,int y) in A is overloading.

Examiner line. For Java/OOP intro, define the term, give a short syntax/example, state compile-time vs runtime behavior, and name the access/package rule involved.

2. Exception Handling

Recall anchor. Exception handling separates normal flow from error recovery. Use try-catch-finally, throw/throws, and proper checked/unchecked exception design.

Scored points.

  • Throwable has two main branches: Error (serious JVM/resource issues, usually not handled) and Exception (application conditions). RuntimeException and subclasses are unchecked.
  • Checked exceptions must be caught or declared with throws; unchecked exceptions occur at runtime (e.g., NullPointerException, ArithmeticException).
  • try encloses risky code, catch handles specific exceptions from most specific to general, finally executes for cleanup whether exception occurs or not.
  • throw creates/raises an exception; throws declares possible exceptions in method signature. Custom exceptions extend Exception or RuntimeException.
  • Byte streams (InputStream/OutputStream) handle binary data; character streams (Reader/Writer) handle text with encoding. Buffered streams improve I/O efficiency.
  • Multithreading: thread states include new, runnable, blocked/waiting/timed waiting, terminated; create by extending Thread or implementing Runnable/Callable; synchronize shared data with locks/synchronized.

Formula strip.

try→catch(E1 ⁣→ ⁣En)→finally,Checked:declare/catch,Unchecked:RuntimeException\texttt{try}\to\texttt{catch}(E_1\!\to\!E_n)\to\texttt{finally},\quad \text{Checked}: \text{declare/catch},\quad \text{Unchecked}: \text{RuntimeException}

Micro-example. try { int r=10/0; } catch(ArithmeticException e){ log(e); } finally { close(); } — catch handles divide-by-zero, finally always runs for cleanup.

Examiner line. For exception/I-O/thread questions, identify exception type, show try-catch-finally or thread lifecycle, and state the JVM/control-flow outcome.

3. Java New Features

Recall anchor. Modern Java emphasizes functional style, immutability, and concise syntax. Lambdas/streams operate on behavior; records/sealed classes model data and restricted hierarchies.

Scored points.

  • Functional interface has exactly one abstract method (e.g., Runnable, Comparator, Predicate); @FunctionalInterface helps enforce the contract.
  • Lambda expression syntax: (params) -> expression/body; it provides concise implementation for functional interfaces and enables functional programming style.
  • Method references (Class::staticMethod, obj::instanceMethod, Class::instanceMethod, Class::new) are shorthand for lambdas that only call an existing method/constructor.
  • Stream API processes collections declaratively: source → intermediate operations (filter, map, sorted) → terminal operation (collect, forEach, reduce); streams are lazy and usually single-use.
  • Java enhancements: default/static interface methods, try-with-resources, Optional, Base64, forEach, diamond with anonymous class, local variable var, switch expressions, text blocks, records.
  • Records provide compact immutable data carriers with generated constructor/accessors/equals/hashCode/toString; sealed classes restrict which classes may extend/implement them.

Formula strip.

λ:(args)→body,Stream:source→filter/map/sort→reduce/collect,record R(T x){}\lambda:(args)\to body,\quad \text{Stream}: source \to filter/map/sort \to reduce/collect,\quad \texttt{record R(T x)\{\}}

Micro-example. List<Integer> evens = nums.stream().filter(n -> n%2==0).map(n -> n*n).toList(); creates a new list of squared even numbers without explicit loop mutation.

Examiner line. For Java features, name the feature, show minimal syntax, explain compile/runtime behavior, and state when it improves readability/safety over older Java.

4. Java Collections Framework

Recall anchor. Collections framework provides reusable data structures and algorithms. Choose interface first: List, Set, Queue/Deque, or Map.

Scored points.

  • Collection hierarchy: Iterable → Collection → List/Set/Queue; Map is separate (key-value). Interfaces define behavior; implementations define performance/storage.
  • List preserves order and allows duplicates: ArrayList (dynamic array, fast random access), LinkedList (node links, good inserts/deletes at ends/iterator), Vector/Stack legacy synchronized.
  • Set stores unique elements: HashSet (hash table, no order), LinkedHashSet (insertion order), TreeSet (sorted, NavigableSet, requires comparable/comparator).
  • Map stores unique keys: HashMap (hash table), LinkedHashMap (insertion/access order), TreeMap (sorted keys), Hashtable (legacy synchronized, no null key/value).
  • Iteration and sorting: Iterator/ListIterator/enhanced for; Comparable defines natural order (compareTo), Comparator defines external/custom order (compare).
  • Utility classes: Collections and Arrays provide sort, search, reverse, shuffle, unmodifiable wrappers; generics provide type safety and reduce casting.

Formula strip.

List:ordered+duplicates,Set:unique,Map:K→V,compareTo/compare∈{−,0,+}\texttt{List}: \text{ordered+duplicates},\quad \texttt{Set}: \text{unique},\quad \texttt{Map}: K\to V,\quad \texttt{compareTo/compare}\in\{-,0,+\}

Micro-example. Map<String,Integer> freq=new HashMap<>(); for(String w:words) freq.put(w,freq.getOrDefault(w,0)+1); counts word occurrences in O(n) average time.

Examiner line. For collections, pick the interface, justify implementation by ordering/uniqueness/complexity, show generic syntax, and mention iterator/comparator behavior.

5. Spring Framework

Recall anchor. Spring uses IoC/DI to manage objects and dependencies. Spring Boot accelerates setup with auto-configuration, starters, and embedded servers.

Scored points.

  • Inversion of Control (IoC) moves object creation/lifecycle to container; Dependency Injection (DI) supplies dependencies via constructor, setter, or field injection (constructor preferred).
  • Spring beans have scopes: singleton (default), prototype, request, session, application, websocket; lifecycle callbacks include init/destroy methods and annotations.
  • Annotations such as @Component, @Service, @Repository, @Controller, @Autowired, @Configuration, @Bean declare and wire components.
  • AOP separates cross-cutting concerns (logging, security, transactions) using aspects, advice, join points, and pointcuts without polluting business logic.
  • Spring Boot provides starters, auto-configuration, embedded Tomcat/Jetty, actuator, and opinionated defaults; main class uses @SpringBootApplication.
  • REST in Spring: @RestController, @RequestMapping/@GetMapping/@PostMapping/@PutMapping/@DeleteMapping, @PathVariable, @RequestParam, @RequestBody map HTTP APIs.

Formula strip.

IoC container+DI⇒loose coupling,REST:HTTP method+URI+status+body\text{IoC container} + \text{DI} \Rightarrow \text{loose coupling},\quad \text{REST}: \text{HTTP method} + \text{URI} + \text{status} + \text{body}

Micro-example. @RestController class UserApi { @GetMapping("/users/{id}") User get(@PathVariable int id){ return svc.find(id); } } maps GET /users/5 to service lookup and returns JSON.

Examiner line. For Spring, define IoC/DI or REST mapping, show the annotation-based code shape, and explain how container/configuration removes boilerplate.

Memory map

%%{init: {'theme': 'base', 'look': 'handDrawn', 'themeVariables': {'fontFamily': "'Nunito', sans-serif", 'fontSize': '17px', 'primaryColor': '#EFEAD6', 'primaryBorderColor': '#0F766E', 'lineColor': '#23211C'}}}%%
flowchart LR
  U1["U1: Introduction"] --> U1a["JVM/JRE/JDK, OOP pillars"] --> U1b["Class, inheritance, interface, package"]
  U1b --> U2["U2: Exception Handling"] --> U2a["try/catch/finally, throw/throws"] --> U2b["I/O streams, threads, synchronization"]
  U2b --> U3["U3: Java New Features"] --> U3a["Lambda, functional interface, streams"] --> U3b["Records, sealed classes, switch/text blocks"]
  U3b --> U4["U4: Java Collections Framework"] --> U4a["List/Set/Queue/Map choices"] --> U4b["Iterator, Comparable/Comparator"]
  U4b --> U5["U5: Spring Framework"] --> U5a["IoC/DI, beans, AOP"] --> U5b["Spring Boot REST annotations"]

Rapid recall

  1. U1 Introduction — JDK/JRE/JVM roles; OOP pillars; overloading compile-time, overriding runtime; abstract class vs interface; packages/JAR.
  2. U2 Exception Handling — Checked vs unchecked; try-catch-finally-throw-throws; byte/character streams; thread lifecycle and synchronization.
  3. U3 Java New Features — Functional interface + lambda + method reference; Stream pipeline; records/sealed classes/var/switch expressions/text blocks.
  4. U4 Java Collections Framework — Choose List/Set/Map by order, uniqueness, key-value; HashMap/TreeSet/ArrayList trade-offs; Comparable vs Comparator.
  5. U5 Spring Framework — IoC/DI and bean scopes; AOP for cross-cutting concerns; Spring Boot REST mappings with @RestController and HTTP annotations.

Final-answer checklist (BCS403)

  • Start with the Java/Spring term definition and the exact API/keyword in backticks.
  • Give a tiny code-shaped example or syntax line when the question asks for implementation.
  • For OOP/collections, compare alternatives by behavior: ordering, duplicates, mutability, complexity, or coupling.
  • For exceptions/threads/Spring, state lifecycle or control flow in order (throw/catch/finally, thread states, request mapping).
  • Close with the practical use-case: when to use the class/interface/feature in a real program.