As most of my experience lies in C++, when i started gaining interest in Java/J2SE i started looking at it from a C++ programmers point of view. Hence the first thing i googled was how to create a canonical class in Java. And i was astonished to find out that the way we do Assignment operator in C++ is not the same in Java. After some more googling i came to know about the clonable interface in Java. And it gave me the right direction...
Then i googled about the String class in Java and found out that a String object in Java is immutable... i became curious and opened the String class of Java... And voila... no wonder... the character array that holds the contents of the String object is final... hence it is immutable... So i asked myself what happens when we do String newString = oldString in Java. And i got the answer... As the String class is not implementing the Clonable interface, when we do String newString = oldString, the oldString's contents get a new reference in newString... We loose any reference to oldString.
But then i wondered how String S1 = oldString + "abc" would work. Because as i was googling i found out that Java does not support operator overloading... so how come the + operator is working fine for the String class? my first stumbling block... fortunately i found out the document at http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1 and my doubts were gone...
So i wondered if Strings are immutable in Java, are not there any way to change the contents of a String object without creating a new object? i googled a little more and came to know about StringBuffer and StringBuilder classes and their mutable char array which will store that data... i delved into the classes a little more and found out about their append function.
So far my investigation into the Java source code is fruitful...
Hopefully i will be able to delve more into it and find out the nitty-gritties about the Java language...
No comments:
Post a Comment