Strings and Chars
Dear Forumers...
I was learning about char's and strings today.......... and was quite surprised to find that they are practically the same.....
I mean a string is basically an array of characters..... so if that is the case then why would it be necessary to have both... I mean people could do everything they wanted from a character array with a string...... so why would anyone want to use char[ ] when they could just use String.... !! Or is there some efficiency factor to this ?
Hopefully my question hasn't been too confusing......
[565 byte] By [
ibn_aziza] at [2007-10-2 22:13:11]

Actually, they are not "practically the same" at all. A char[] is a basic type array with limited functionality. While its size isn't mutable, its contents are. Basically, it provides a fixed size storage container for characters.
A String is much richer, immutable Object that provides storage for one specific string of characters, as well as methods to transform one String into another. String uses a char[] internally.
A char[] might make sense when all you need is a fixed size set of characters that needs to be manipulated on a character-by-character basis.
Sometimes it's easier to operate on char array, especially when you
want to change it's content. Consider swapping the first and the last
letter. Compare both String and char[] algorithms.
There are also StringBuffer and StringBuilder types, both mutable, which behave pretty much the same like the String.
StringBuffer is synchronized, StringBuilder ain't.