Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer...

 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,i got it from http://www.go4java.20m.com/mock1.htm

class outerex
{
public static void main(String args[])
{
String s[]={"A","B"};

System.out.println(s[0]+","+s[1]);
}
}

here i am getting error as incompatible types. if i use StringBuffer s[]=new StringBuffer[]("A","B"};

then it's working. why so?

Preparing Scjp 5
 
James Tharakan
Ranch Hand
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure you got such a error???
I just now Compiled and i was able to run the program without any knid of problem and with the expected results.
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please replace this String s[]={"A","B"} with
StringBuffer[] s={"A","B"};
sorry i posted the wrong one which is irrelevant to my question.
now you check with this...
 
Ankit Garg
Sheriff
Posts: 9509
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arun you can intialize String array with the syntax

String[] arr = {"a", "b"};

because this is just a shortcut provided to you by the compiler (just like autoboxing etc) to make String class feel like a primitive type. But this shortcut is not applicable to any other type. So when you write this

StringBuffer[] arr = {"a","b"};

compiler changes the right hand part of the = operator and makes it new String[]{"a", "b"} so you get the inconvertible error message as String and StringBuffer classes are not related to each other...
 
Rekha Srinath
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Adding to what Ankit said, the right statement here would be:

StringBuffer s[]=new StringBuffer[]{new StringBuffer("A"),new StringBuffer("B")};
 
Preethi Dev
Ranch Hand
Posts: 265
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks...i got it .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic