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]
# 1

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.

Herko_ter_Horsta at 2007-7-14 1:30:00 > top of Java-index,Java Essentials,New To Java...
# 2
Ok... that makes more sense... but if I remember correctly I think I remember reading somewhere that there are two types of strings... mutable and immutable... please correct me if I am wrong......much appreciated..as I have understood the general concept ......
ibn_aziza at 2007-7-14 1:30:00 > top of Java-index,Java Essentials,New To Java...
# 3

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.

maf69a at 2007-7-14 1:30:00 > top of Java-index,Java Essentials,New To Java...
# 4
There is no such type of 'string'. There is a String class that is immutable.JJ
Java_Jaya at 2007-7-14 1:30:00 > top of Java-index,Java Essentials,New To Java...