This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer..." Watch "StringBuffer..." New topic


Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
Hi,i got it from

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


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

Joined: Aug 29, 2008
Posts: 580

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.

Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Preethi Dev
Ranch Hand

Joined: Sep 07, 2008
Posts: 265
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

Joined: Aug 03, 2008
Posts: 9466

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...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
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

Joined: Sep 07, 2008
Posts: 265
Thanks...i got it .
I agree. Here's the link:
subject: StringBuffer...
It's not a secret anymore!