Hi All, We can create a String class as: String s1="sample"; But we can't create a StringBuffer as: StringBuffer s1="sample"; Can you please explain the reason for this other than syntax. thankyou, saimurali ------------------ saimurali
From what I understand. When the compiler comes across this String s = "hello" it creates a string object & stores it in a string pool. But to create a StringBuffer object you have to use its contructor. Any body else please correct me or add more explanation
Originally posted by sai murali: Hi All, We can create a String class as: String s1="sample"; But we can't create a StringBuffer as: StringBuffer s1="sample"; Can you please explain the reason for this other than syntax. thankyou, saimurali
String s = "Ragu"; This is created on a string pool of litreals StringBuffer s = "Ragu"; //There is no constructor like this Always remember Strings are immutable But StringBuffers arent Ragu
posted 17 years ago
Roopa and Ragu, I got what you were telling, but we can construct a String using constructor also as: String s1=new String("java"); But only Strings declaration allows to create a String object as: String s1="java"; I just want to know is there any other specific reason for allowing like this. thank you....
String objects constructed with String literals are allowed for optimization purposes. When you construct a String object that way, the String is automatically interned in the private String pool of your class if not already present. This is to prevent flooding the memory with lots of String object that are equals and since String objects are immutable (unlike String represented by StringBuffer) this does no harm to your program and one String instance may be reference by many references. HIH ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform