Nearby lessons

112 of 125

Java - StringTokenizer

📌 What You Will Learn
  • Why String objects are immutable
  • String vs StringBuffer vs StringBuilder
  • The most important methods of String
  • == vs equals() — the classic interview question
  • How to split, join and manipulate text

StringTokenizer is a core concept of the Java language. This lesson explains String Tokenization — StringTokenizer with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

String Tokenization — StringTokenizer

String tokenization means splitting a String into tokens (small pieces). The classic tool is java.util.StringTokenizer (note: it is legacy now — String.split() is the modern replacement — but it still appears in exams).

The three methods to remember: countTokens() (how many pieces), hasMoreTokens() (is there another piece?), nextToken() (give the next piece). Modern equivalent: "Java is powerful".split(" ").

Example01
JCode Cell
1import java.util.StringTokenizer;
2 
3class TokenDemo {
4 public static void main(String[] args) {
5 StringTokenizer st = new StringTokenizer("Java is powerful");
6 System.out.println("No of tokens: " + st.countTokens());
7 
8 while (st.hasMoreTokens()) { // cursor moves token by token
9 System.out.println(st.nextToken());
10 }
11 }
12}
Output
No of tokens: 3 Java is powerful
📝 Key Takeaways
  • String is a class, not a primitive; it is immutable.
  • Immutability gives security, thread safety and pool caching.
  • Use StringBuilder (fastest, not thread-safe) or StringBuffer (thread-safe) when text changes often.
  • == compares references; .equals() compares content. Always use .equals() for Strings.
  • Override toString() to print objects meaningfully.
  • Text blocks (Java 15+) make multi-line strings clean.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2