Java Reference
In-Depth Information
if (len <= 1) {
return true;
}
// Convert the string into uppercase,
// so we can make the comparisons case insensitive
String newStr = inputString.toUpperCase();
// Initialize the result variable to true
boolean result = true;
// Get the number of comparisons to be done
int counter = len / 2;
// Do the comparison
for (int i = 0; i < counter; i++) {
if (newStr.charAt(i)!= newStr.charAt(len - 1 - i)) {
// It is not a palindrome
result = false;
// Exit the loop
break;
}
}
return result;
}
}
hello is a palindrome: false
noon is a palindrome: true
StringBuilder and StringBuffer
StringBuilder and StringBuffer are companion classes for the String class. Unlike a String , they represent a
mutable sequence of characters. That is, you can change the content of StringBuilder and StringBuffer without
creating a new object. You might wonder why two classes exist to represent the same thing—a mutable sequence of
characters. The StringBuffer class has been part of the Java library since the beginning whereas the StringBuilder
class was added in Java 5. The difference between the two lies in thread safety. StringBuffer is thread-safe and
StringBuilder is not thread-safe. Most of the time, you do not need thread safety and using StringBuffer in those
cases has a performance penalty. This is the reason that StringBuilder was added later. Both classes have the same
methods, except that all methods in StringBuffer are synchronized. I will discuss only StringBuilder in this section.
Using StringBuffer in your code would be just a matter of changing the class name.
Use StringBuilder when no thread safety is needed, for example, manipulating a sequence of characters in a
local variable in a method or constructor. Otherwise, use StringBuffer . thread safety and synchronization are described
in Chapter 8 in Beginning Java Language Features (iSBn 978-1-4302-6658-7).
Tip
 
 
Search WWH ::




Custom Search