Programs & Examples
Strings and StringBuilder · Study material
Word and vowel statistics of a sentence
toLowerCase, replaceAll with a regex, split on whitespace and indexOf combine into a small text-analysis program.
public class Main {
public static void main(String[] args) {
String text = "Java is easy to learn. Java is powerful, and Java is everywhere!";
String[] words = text.toLowerCase().replaceAll("[^a-z ]", "").split("\\s+");
int vowels = 0;
for (char ch : text.toLowerCase().toCharArray()) if ("aeiou".indexOf(ch) >= 0) vowels++;
String longest = "";
int javaCount = 0;
for (String w : words) {
if (w.length() > longest.length()) longest = w;
if (w.equals("java")) javaCount++;
}
String capitalised = Character.toUpperCase(longest.charAt(0)) + longest.substring(1);
System.out.println("words: " + words.length + ", vowels: " + vowels + ", 'java' x" + javaCount + ", longest: " + capitalised);
}
}
words: 12, vowels: 22, 'java' x3, longest: Everywhere
StringBuilder editing operations
The StringBuilder example chains append, insert, replace, delete, reverse and setCharAt on one mutable object.
JSON with a text block
The text-block example builds a JSON document with formatted() – no escaped quotes or newline characters needed.