Give the capacity after the given number of add() calls: (a) new Vector<>() after 21 adds; (b) new Vector<>(3) after 7 adds; (c) new Vector<>(3, 2) after 7 adds.
Java 1.0's legacy utility classes still appear in exams: Vector (a synchronized growable array), Stack (LIFO on top of Vector), the Observer/Observable pair (the observer pattern, deprecated since Java 9), StreamTokenizer (splits a character stream into words and numbers), plus Hashtable and Enumeration.
update(Observable o, Object arg). Observable offers addObserver, deleteObserver, setChanged (protected) and notifyObservers(arg). Both deprecated since Java 9.JDK 1.0 (1996) shipped only a handful of data-structure classes: Vector, Stack, Hashtable, the abstract Dictionary, Properties, BitSet and the Enumeration interface, plus Observer/Observable and the tokenizers. Java 1.2 (1998) introduced the Collections Framework designed by Joshua Bloch — the List, Set and Map interfaces with ArrayList, LinkedList, HashMap and friends. The old classes were retrofitted (Vector now implements List, Hashtable implements Map) and kept for compatibility; Swing's JList and DefaultTableModel still accept Vectors.
| Legacy (JDK 1.0) | Modern replacement |
|---|---|
| Vector | ArrayList (or Collections.synchronizedList, CopyOnWriteArrayList) |
| Stack | ArrayDeque used through the Deque interface |
| Hashtable | HashMap, or ConcurrentHashMap for thread safety |
| Enumeration | Iterator |
| Observer / Observable | java.beans PropertyChangeListener, java.util.concurrent.Flow, custom listener interfaces |
| StringTokenizer | String.split() or Scanner |
| StreamTokenizer | Scanner or regular expressions (StreamTokenizer remains supported) |
A Vector stores elements in an internal array, reached by index from 0 to size − 1, and grows automatically when that array fills up. Every public method is synchronized, so a Vector is thread-safe — and correspondingly slower in single-threaded code. Since Java 5 it is generic: Vector<String>. Two numbers describe it: size(), how many elements it holds, and capacity(), how long its internal array currently is.
| Constructor | Initial capacity | When full |
|---|---|---|
| Vector() | 10 | Capacity doubles |
| Vector(int initialCapacity) | initialCapacity | Capacity doubles |
| Vector(int initialCapacity, int capacityIncrement) | initialCapacity | Capacity grows by capacityIncrement (if it is > 0) |
| Vector(Collection c) | c's size | Capacity doubles |
| Method | What it does |
|---|---|
| addElement(obj) / add(obj) | Append at the end (add also returns true) |
| insertElementAt(obj, index) | Insert obj at index and shift the rest right — object first |
| add(index, obj) | The List-style equivalent — index first |
| elementAt(i) / get(i) | The element at i (ArrayIndexOutOfBoundsException if i is invalid) |
| firstElement() / lastElement() | First / last element (NoSuchElementException when empty) |
| setElementAt(obj, i) / set(i, obj) | Replace the element at i |
| removeElement(obj) | Remove the first occurrence of obj; returns true if it was found |
| removeElementAt(i) / remove(i) | Remove the element at index i |
| removeAllElements() | Remove everything (the capacity stays the same) |
| indexOf(obj) / contains(obj) | Search using equals() |
| size() / capacity() | Number of elements / length of the internal array |
| elements() | An Enumeration over the elements |
| trimToSize() / ensureCapacity(n) / setSize(n) | Shrink the array to fit / reserve room / truncate or pad with nulls |
import java.util.Enumeration;
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector<String> v = new Vector<>(3, 2); // capacity 3, grows by 2
v.addElement("Kochi");
v.addElement("Thrissur");
v.addElement("Kollam");
System.out.println(v.size() + " " + v.capacity()); // 3 3
v.addElement("Kannur"); // full: grows 3 -> 5
System.out.println(v.size() + " " + v.capacity()); // 4 5
v.insertElementAt("Idukki", 1); // object first, then index
System.out.println(v); // [Kochi, Idukki, Thrissur, Kollam, Kannur]
System.out.println(v.elementAt(2) + " " + v.firstElement() + " " + v.lastElement());
// Thrissur Kochi Kannur
v.removeElement("Kollam"); // by value
v.removeElementAt(0); // by index: removes Kochi
Enumeration<String> e = v.elements();
while (e.hasMoreElements())
System.out.print(e.nextElement() + " "); // Idukki Thrissur Kannur
System.out.println("| size " + v.size() + ", capacity " + v.capacity()); // size 3, capacity 5
}
}insertElementAt(obj, index) and setElementAt(obj, index) take the object first, while add(index, obj) and set(index, obj) take the index first.| Point | Vector | ArrayList |
|---|---|---|
| Introduced | JDK 1.0 (retrofitted to List in 1.2) | Java 1.2 (Collections Framework) |
| Synchronized? | Yes — every public method | No (wrap with Collections.synchronizedList if needed) |
| Single-thread speed | Slower: locks on every call | Faster |
| Growth when full | Doubles (or + capacityIncrement) | Grows by 50%: new = old + old/2 |
| Default capacity | 10, allocated at once | 10, allocated on the first add in recent JDKs |
| Capacity control | capacity(), capacityIncrement | ensureCapacity(), trimToSize(); no capacity() method |
| Traversal | Enumeration (elements()) and Iterator | Iterator and ListIterator |
| Fail-fast? | Its Iterator is; its Enumeration is not | Its Iterator is |
Stack<E> extends Vector<E> and adds the five classic stack operations. It has a single no-argument constructor. Internally the top of the stack is the end of the vector, which is why toString() prints the elements from bottom to top.
| Method | Returns | Notes |
|---|---|---|
| push(E item) | the item pushed | Adds on top (same effect as addElement) |
| pop() | the top item | Removes it; EmptyStackException if the stack is empty |
| peek() | the top item | Does not remove it; EmptyStackException if empty |
| empty() | boolean | true when there are no items (isEmpty() is inherited too) |
| search(Object o) | int | 1-based distance from the top — the top is 1; −1 if not found |
import java.util.EmptyStackException;
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack<String> s = new Stack<>();
s.push("A"); s.push("B"); s.push("C"); // bottom A, B, C top
System.out.println(s); // [A, B, C] (bottom to top)
System.out.println(s.peek()); // C
System.out.println(s.search("C") + " " + s.search("A") + " " + s.search("Z")); // 1 3 -1
System.out.println(s.pop() + " " + s.pop()); // C B
System.out.println(s.empty() + " " + s.size()); // false 1
s.pop(); // removes A
try {
s.pop(); // nothing left
} catch (EmptyStackException e) {
System.out.println("EmptyStackException caught");
}
}
}static boolean balanced(String expr) {
Stack<Character> st = new Stack<>();
for (char ch : expr.toCharArray()) {
if (ch == '(' || ch == '[' || ch == '{') st.push(ch);
else if (ch == ')' || ch == ']' || ch == '}') {
if (st.empty()) return false; // a closer with nothing open
char open = st.pop();
if ((ch == ')' && open != '(') || (ch == ']' && open != '[') || (ch == '}' && open != '{'))
return false; // the wrong kind of bracket
}
}
return st.empty(); // was every bracket closed?
}
// balanced("{a[b(c)]}") -> true balanced("(a]") -> false balanced("((") -> falseBecause a Stack is a Vector, it also inherits add(index, x), get(i) and remove(i), so nothing stops code from inserting into the middle — the LIFO discipline is not enforced. This is the textbook example of misused inheritance; the Java documentation now recommends Deque<E> st = new ArrayDeque<>(); with push, pop and peek (where pop on an empty deque throws NoSuchElementException and peek returns null).
The observer pattern connects one subject to many observers: when the subject's state changes, every registered observer is notified automatically. The subject knows only that its observers implement a common interface, so new kinds of observers can be added without touching it. Publish–subscribe systems, spreadsheet charts and the views in MVC all work this way.
void update(Observable o, Object arg).addObserver(Observer), deleteObserver(Observer), deleteObservers(), countObservers(), hasChanged(), the protected setChanged() and clearChanged(), and notifyObservers() / notifyObservers(Object arg).setChanged() and then notifyObservers(arg). If the changed flag is set, every observer's update() is called with the subject and arg, and the flag is cleared.import java.util.Observable;
import java.util.Observer;
class AllotmentBoard extends Observable { // the subject
private int flatsLeft = 10;
void allot(int n) {
flatsLeft -= n;
setChanged(); // mark the state as changed (protected)
notifyObservers(flatsLeft); // calls update() on every observer
}
}
class Display implements Observer { // an observer
private final String where;
Display(String where) { this.where = where; }
public void update(Observable o, Object arg) {
System.out.println(where + ": flats left = " + arg);
}
}
public class ObserverDemo {
public static void main(String[] args) {
AllotmentBoard board = new AllotmentBoard();
board.addObserver(new Display("Kochi office"));
board.allot(3);
board.allot(2);
System.out.println(board.countObservers());
}
}Two design weaknesses show here. Observable is a class, so a subject must spend its single superclass on it; and setChanged() is protected, so only a subclass can mark a change. Updates run synchronously in the thread that calls notifyObservers(), and the order in which observers are called is not specified.
PropertyChangeSupport/PropertyChangeListener (java.beans), the concurrent queues, the reactive java.util.concurrent.Flow API, or a listener interface of your own. They remain in the JDK and on the syllabus.java.io.StreamTokenizer reads characters from a Reader and breaks them into tokens, telling you for each one whether it is a word, a number, an end of line, the end of the input, or a single 'ordinary' character such as + or ,. It is handy for simple parsers, calculators and configuration readers. Create it with new StreamTokenizer(Reader r); the InputStream constructor has been deprecated since Java 1.1.
| Member | Meaning |
|---|---|
| int nextToken() | Read the next token and return its type (also stored in ttype) |
| int ttype | The type of the current token |
| TT_WORD (−3) | A word; its text is in sval |
| TT_NUMBER (−2) | A number; its value is in nval, always a double |
| TT_EOL ('\n', i.e. 10) | End of line — reported only after eolIsSignificant(true) |
| TT_EOF (−1) | End of the stream |
| Any other value | An ordinary character; ttype is the character itself, e.g. '+' or ',' |
| String sval | Text of a word, or the body of a quoted string (ttype is then the quote character) |
| double nval | Value of a number token |
| lineno() / pushBack() | Current line number / make the next nextToken() return the current token again |
| Configuration method | Effect |
|---|---|
| eolIsSignificant(boolean) | If true, line ends come back as TT_EOL (default false: they count as whitespace) |
| ordinaryChar(ch) / ordinaryChars(lo, hi) | Make characters plain single-character tokens |
| whitespaceChars(lo, hi) | Treat these characters as separators |
| wordChars(lo, hi) | Characters that may form words |
| quoteChar(ch) | Delimiter of quoted strings (' and " by default) |
| commentChar(ch) | Ignore the rest of the line after ch — '/' by default |
| slashSlashComments / slashStarComments(boolean) | Recognise // and /* … */ comments |
| lowerCaseMode(boolean) | Convert every word to lower case |
| parseNumbers() / resetSyntax() | Recognise numbers (on by default) / make every character ordinary |
The default syntax: letters (A–Z, a–z and accented Latin-1 letters) are word characters; codes 0–32 (space, tab, newline) are whitespace; digits, . and - start numbers — and may also continue a word, so "x2" and "e-mail" come back as single words; ' and " delimit strings; / starts a comment.
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
public class TokenCount {
public static void main(String[] args) throws IOException {
String text = "Total 100 questions\nTime 90 minutes, marks 100\n";
StreamTokenizer st = new StreamTokenizer(new StringReader(text));
st.eolIsSignificant(true); // report line ends as TT_EOL
int words = 0, numbers = 0, lines = 0, others = 0;
double sum = 0;
while (st.nextToken() != StreamTokenizer.TT_EOF) {
switch (st.ttype) {
case StreamTokenizer.TT_WORD: words++; break; // text in st.sval
case StreamTokenizer.TT_NUMBER: numbers++; sum += st.nval; break;
case StreamTokenizer.TT_EOL: lines++; break;
default: others++; // here: the ','
}
}
System.out.println(words + " words, " + numbers + " numbers (sum " + sum + "), "
+ lines + " lines, " + others + " other");
}
}| StreamTokenizer | StringTokenizer | Scanner | String.split | |
|---|---|---|---|---|
| Package | java.io | java.util | java.util | java.lang (String) |
| Input | Any Reader (a stream) | One String | String, File or InputStream | One String |
| Token types | Word, number (double), EOL, EOF, ordinary character | Every token is a String | Typed reads: nextInt(), nextDouble(), next() | A String[] |
| Separators | A configurable syntax table | A set of delimiter characters | A regular expression (whitespace by default) | A regular expression |
| Status | Legacy but supported | Legacy — split() or regex preferred | Modern (Java 5) | Modern (Java 1.4) |
Hashtable (JDK 1.0) maps keys to values using hashing. Like Vector, all its methods are synchronized. It extends the obsolete abstract class Dictionary and has implemented Map since 1.2. It rejects null keys and values (NullPointerException), starts with capacity 11 and load factor 0.75, and on rehashing grows to 2 × old + 1. Its legacy keys() and elements() return Enumerations, and contains(value) searches the values.
import java.util.Enumeration;
import java.util.Hashtable;
public class Table {
public static void main(String[] args) {
Hashtable<String, Integer> seats = new Hashtable<>();
seats.put("Kochi", 120);
seats.put("Kannur", 60);
seats.put("Kochi", 130); // same key: the value is replaced
System.out.println(seats.get("Kochi") + " " + seats.size());
System.out.println(seats.containsKey("Kannur") + " " + seats.contains(60));
Enumeration<String> keys = seats.keys();
int total = 0;
while (keys.hasMoreElements()) total += seats.get(keys.nextElement());
System.out.println("total " + total);
// seats.put(null, 1); // NullPointerException (HashMap allows it)
}
}| Point | Hashtable | HashMap |
|---|---|---|
| Introduced | JDK 1.0, extends Dictionary | Java 1.2, extends AbstractMap |
| Synchronized? | Yes | No |
| null keys / values | Not allowed (NullPointerException) | One null key and any number of null values |
| Default capacity | 11, load factor 0.75 | 16, load factor 0.75 |
| Traversal | Enumeration (keys(), elements()) and Iterator | Iterator over keySet(), values(), entrySet() |
| Thread-safe modern choice | ConcurrentHashMap | ConcurrentHashMap |
Properties extends Hashtable for string configuration data: getProperty(key, default), setProperty, and load() / store() to read and write .properties files; System.getProperties() returns the JVM's own settings. BitSet is a growable vector of bits, and Dictionary is the abstract parent of Hashtable — both are rarely used directly today.
Try the problem first, then reveal the working one step at a time.
Give the capacity after the given number of add() calls: (a) new Vector<>() after 21 adds; (b) new Vector<>(3) after 7 adds; (c) new Vector<>(3, 2) after 7 adds.
Predict: push(10); push(20); push(30); then peek(), search(10), pop(), push(40), search(20), search(40), and finally the stack printed with toString() and its size().
With the default StreamTokenizer settings, list each token (its ttype and value) for the input x = 25 + y2;.
A subclass of Observable has two registered observers. Its method update(int v) { this.value = v; notifyObservers(v); } is called, yet neither observer prints anything. Diagnose and fix.
A default Vector and a default ArrayList each receive 21 add() calls. What is the Vector's capacity? What is the ArrayList's internal capacity (not visible through its API)?
Predict each value: Stack<Integer> s = new Stack<>(); s.push(5); s.push(10); s.push(15); then s.search(5), s.pop(), s.search(5), s.peek(), s.search(99).
Why can't a class that already extends javax.swing.JFrame act as an Observable subject, and why can't ordinary code call setChanged() on someone else's Observable?
With default StreamTokenizer settings, what tokens does the input Rs. 4,500 only produce?
State one difference each between (a) Hashtable and HashMap regarding null, (b) Enumeration and Iterator regarding removal, (c) StreamTokenizer and StringTokenizer regarding the type of tokens.
insertElementAt(obj, index) and setElementAt(obj, index) take the object first; add(index, obj) and set(index, obj) take the index first.search() is 1-based and counts from the top (top = 1, −1 if absent) — unlike the 0-based index used by get() and elementAt().empty() (isEmpty() also works, inherited); pop()/peek() on an empty Stack throw EmptyStackException rather than returning null.10/2 yields only the number 10.0 unless you call ordinaryChar('/').10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
new Vector() isModelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.