Unit 5 · Applying Java OOP · 9 min
Strings and ArrayList
String handles text and is immutable. ArrayList is a resizable array that grows as you add items.
Why this matters
Almost every project stores a list of objects — students, books, products — and ArrayList is the simplest way to do it.
Example
Java
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) {
String name = " Ananya Rao ";
System.out.println(name.trim().toUpperCase());
System.out.println("Length: " + name.trim().length());
System.out.println(name.contains("Rao"));
ArrayList<String> subjects = new ArrayList<>();
subjects.add("Java");
subjects.add("DBMS");
subjects.add("Maths");
subjects.remove("Maths");
for (String s : subjects) {
System.out.println("Subject: " + s);
}
System.out.println("Count: " + subjects.size());
}
}Output
ANANYA RAO Length: 10 true Subject: Java Subject: DBMS Count: 2
Step by step
- 1`trim()` removes spaces at both ends; `toUpperCase()` returns a new uppercase String.
- 2String is immutable: these methods return new Strings, the original never changes.
- 3`length()` is a method for Strings (arrays use the field `length`).
- 4`ArrayList<String>` is a growable list of Strings.
- 5add(), remove() and size() are the three methods you will use most.
- 6The enhanced for loop reads each item in turn.
Key points
- Compare Strings with .equals(), never ==
- String is immutable; StringBuilder is mutable
- ArrayList grows automatically, arrays do not
- Use generics: ArrayList<Student> instead of a raw ArrayList
Common mistakes
- Expecting name.toUpperCase() to change name itself
- Comparing Strings with ==
- Forgetting to import java.util.ArrayList
Try it yourself
- Store five subject names in an ArrayList and print them sorted.
- Count how many vowels a String contains.