Java Notes
Practice essential Java String programs by learning the logic for reversing text, checking a palindrome, and counting characters rather than memorising output.
These programs combine String methods, loops, conditions, and arrays. First understand what each variable represents; then run the code and change the input yourself.
Reverse a String
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The loop begins at the final index and moves backward. charAt(index) reads one character; append() stores it in reverse order. This pattern is useful whenever the required output runs from end to start.
Check whether text is a palindrome
A palindrome reads the same forward and backward, such as level. Comparing a normalised value with its reversed value gives a clear solution.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
toLowerCase() makes case irrelevant, reverse() reverses the builder, and equals() compares characters. For sentences, remove spaces and punctuation before comparing.
Count vowels and consonants
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
The outer condition ignores spaces and punctuation. indexOf(letter) >= 0 means the character is present in the vowel String. Try digits or another sentence to verify why the letter check matters.
Practice next
- Count words after calling
trim()and splitting on one-or-more spaces. - Find the first repeated character by comparing each character with later characters.
- Check two words for anagrams after lowercasing and sorting their character arrays.
Continue the lesson path