Strings (Immutability & Methods) and the Vector Class
1. Topic Introduction
Text handling and resizable storage appear in almost every Java program. Unlike C where strings are raw char[] arrays ending in '\0', Java models strings as immutable java.lang.String objects packed with rich manipulation methods. And when you need an array that grows automatically at runtime, Java provides java.util.Vector.
String) vs Expandable Accordion Folder (Vector)A Java **String** is like an engraved stone tablet: once carved ("KTU"), you cannot erase a letter on that tablet. Calling toUpperCase() or concat() simply carves a brand-new tablet while keeping the original intact! Meanwhile, a **Vector** is an expandable accordion folder—unlike a rigid fixed-size array, whenever you add more items than it currently holds, it automatically doubles or expands its pockets (capacity) to hold objects.
String objects are immutable (methods return new Strings); Vector is a dynamic synchronized array that grows automatically and stores Objects (using Wrapper classes for numbers).3. Essential Exam Definitions
String object's character sequence cannot be modified after creation; operations like replace() or concat() return a newly created String object.java.util capable of growing/shrinking at runtime and storing heterogeneous or generic object references.4. Detailed Technical Explanation & Syntax
Creating Strings & String Constant Pool (== vs .equals())
Java supports two ways to create Strings, with a crucial memory difference often tested in KTU output prediction:
1. String Literal (String s1 = "Java"; String s2 = "Java";): JVM checks the String Constant Pool inside the Heap. Both s1 and s2 point to the EXACT SAME pooled object, so s1 == s2 is true.
2. new Keyword (String s3 = new String("Java");): Forces creation of a separate Heap object outside the pool, so s1 == s3 is false, whereas s1.equals(s3) is true! (Note: Unlike C strings, Java String objects are NOT null-terminated with '\0'; they store exact length internally.)
Important String Methods (Exam Reference)
Memorize these high-frequency String methods and their return types:
int length(): Returns number of characters (remember parentheses!).char charAt(int index): Returns character at 0-based index.boolean equals(Object s)&boolean equalsIgnoreCase(String s): Compares character contents (always prefer over==).int compareTo(String s): Lexicographical comparison returning0(equal),< 0, or> 0(useful for sorting strings).String substring(int begin)/substring(int begin, int end): Extracts slice (begininclusive,endexclusive).int indexOf(String str)/lastIndexOf(...): First/last index of substring, or-1if absent.String toUpperCase()/toLowerCase()/trim()/replace(old, new): Returns transformed newString.String concat(String s)&String[] split(String regex): Joins strings or splits into array.
The Vector Class (java.util.Vector)
Introduced in early Java as a growable array of objects. Remember from your notes: **Vector works with Objects ONLY, so primitive types (int, double) must be wrapped into Wrapper objects (Integer, Double) via autoboxing or valueOf()**.
Constructors: Vector() (default initial capacity 10), Vector(int size), Vector(int size, int incr).
Key Vector Methods: addElement(obj) / add(obj), insertElementAt(obj, index), elementAt(index) / get(index), size() (current count), capacity() (allocated buffer slots), removeElement(obj) / removeElementAt(index), copyInto(array).
5. Working Principle: How String Immutability & Vector Capacity Growth Work
- Executing
String s = "Hello"; s.concat(" World");creates"Hello World"in memory, discards it because it wasn't assigned, and leavesspointing to"Hello"! - You must assign
s = s.concat(" World");to observe the updated reference. - When a
Vectorof default capacity10receives an 11th element, it automatically allocates a new internal array of capacity20(doubles by default unlesscapacityIncrementwas given) and copies references over.
7. Complete Java Code Examples & Tracing
new, String methods, lexicographical sorting, and Vector dynamic growth with wrapper types.| 1 | import java.util.Vector; |
| 2 | |
| 3 | public class StringAndVectorDemo { |
| 4 | public static void main(String[] args) { |
| 5 | // 1. String Pool vs new String() and Immutability |
| 6 | String s1 = "KTU"; |
| 7 | String s2 = "KTU"; |
| 8 | String s3 = new String("KTU"); |
| 9 | System.out.println("s1 == s2 (pool): " + (s1 == s2)); |
| 10 | System.out.println("s1 == s3 (heap): " + (s1 == s3)); |
| 11 | System.out.println("s1.equals(s3): " + s1.equals(s3)); |
| 12 | |
| 13 | s1.concat(" Java"); // Ignored because String is immutable! |
| 14 | System.out.println("After ignored concat: " + s1); |
| 15 | s1 = s1.concat(" Java"); |
| 16 | System.out.println("Length: " + s1.length() + ", Substring(4): " + s1.substring(4)); |
| 17 | |
| 18 | // 2. Vector Class with Objects & Wrapper Types |
| 19 | Vector<Object> items = new Vector<>(2, 3); // initial cap 2, increment 3 |
| 20 | items.addElement("OOP"); |
| 21 | items.addElement(2024); // int autoboxed to Integer |
| 22 | items.addElement(60.0); // Triggers capacity growth: 2 + 3 = 5 |
| 23 | items.insertElementAt("KTU", 0); |
| 24 | |
| 25 | System.out.println("Vector size: " + items.size() + ", capacity: " + items.capacity()); |
| 26 | System.out.println("Element at 1: " + items.elementAt(1)); |
| 27 | items.removeElement(60.0); |
| 28 | System.out.println("Final Vector: " + items); |
| 29 | } |
| 30 | } |
s1 == s2 (pool): true s1 == s3 (heap): false s1.equals(s3): true After ignored concat: KTU Length: 8, Substring(4): Java Vector size: 4, capacity: 5 Element at 1: OOP Final Vector: [KTU, OOP, 2024]
StringVectorequalslengthaddElementcapacity- Using
==instead of.equals()to compare user-entered or newly constructed Strings. - Confusing
Vector.size()(actual element count) withVector.capacity()(allocated buffer size). - Trying to pass raw primitives into
Vectorin pre-Java 5 code without Wrapper classes.
Comparison Tables
| Property | Array (int[]) | Vector (java.util.Vector) |
|---|---|---|
| Size | Fixed once created | Dynamic (grows/shrinks automatically) |
| Data Types Stored | Primitives and Objects | Objects ONLY (primitives need Wrappers) |
| Length Syntax | arr.length (field) | vec.size() & vec.capacity() (methods) |
| Thread Safety | Not synchronized | Synchronized (thread-safe legacy collection) |
| Insertion/Deletion | Manual shifting required | Built-in insertElementAt(), removeElement() |
Real-World Applications
- String pooling saves gigabytes of RAM across web servers handling repeated header/route names.
- Thread-safe legacy systems use
Vector(orArrayListin modern single-threaded contexts) for dynamic item lists.
Important KTU Exam Points
- Always explain WHY
==differs from.equals()on Strings (reference address vs character content). - State at least 5
Stringmethods and 5Vectormethods with exact signatures in 6-mark questions. - Emphasize that
Vectorcannot store raw primitive types directly—Wrapper objects are required.
Memory Techniques & Revision
- String
=== Address Match;.equals()= Content Match. Vector= Synchronized Dynamic Object Bag (Size = inside now, Capacity = max before resize).
Common Pitfalls to Avoid
- Calling
s.toUpperCase();withouts = s.toUpperCase();and expectingsto change. - Writing
substring(1, 4)and expecting 4 characters—end index is EXCLUSIVE, so it extracts indices 1, 2, and 3 (3 chars).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: Both Arrays and java.util.Vector store sequences of elements, but Arrays are fixed-size language constructs whereas Vector is a dynamic, synchronized collection class.
- Size: Arrays have fixed length;
Vectorautomatically grows when capacity is exceeded. - Types: Arrays store both primitives and objects;
Vectorstores objects only (requiring Wrapper classes for primitives). - Key Methods:
addElement(Object obj)appends an item;insertElementAt(Object obj, int index)inserts at position;elementAt(int index)fetches item;size()returns element count;capacity()returns allocated capacity.
| Vector<Integer> v = new Vector<>(); |
| v.addElement(10); // autoboxed to Integer |
| v.addElement(20); |
| System.out.println(v.size() + " / " + v.capacity()); |
Quick Understanding Check
1. What does the following print? String s = "Java"; s.toUpperCase(); System.out.println(s);
2. Which statement is true about java.util.Vector?