Results 1 to 2 of 2
  1. #1
    crazygurl is offline Member
    Join Date
    Oct 2009
    Posts
    6
    Rep Power
    0

    Default Strings as array help please..

    Hi!!
    Can anyone help me?? I am learning array in school, i created an array of strings and the outputs seems different.

    Here is the code:

    public class StringsArray{
    public static void main (String [] args) {

    StringBuffer[] a;
    a = new StringBuffer[4];

    a[0] = new StringBuffer("Sasparilla");
    for (int i = 1; i < 4; i++)
    a[i] = a[0];

    a[1].setCharAt(0, 'J');
    for (int i = 0; i < 4; i++)
    System.out.println(a[i]);

    }
    }

    I need to print
    sasparilla
    jasparilla
    sasparilla
    sasparilla

    but the program is only printing jasparilla 4 times. Can anyone tell me why this is so please??????

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    All array positions refer to the same StringBuffer object. To have them be different, they all should refer to a different StringBuffer. Therefore, you'll need to create a newStringBuffer for each array item (in your for loop). Also, please try to use code tags (see my signature below) to help make your posted code readable.

    Much luck!

Similar Threads

  1. 2 dimensional array with strings.
    By dbashby in forum New To Java
    Replies: 12
    Last Post: 10-13-2009, 10:52 PM
  2. Need help with counting strings in an array.
    By dalonehunter in forum New To Java
    Replies: 1
    Last Post: 10-02-2009, 08:47 AM
  3. storing strings into an array
    By anthonym2121 in forum New To Java
    Replies: 2
    Last Post: 04-04-2009, 07:32 AM
  4. To find the Maximum and Minimum in an Array of Strings
    By luscious in forum JavaServer Pages (JSP) and JSTL
    Replies: 9
    Last Post: 07-31-2008, 01:51 PM
  5. Sorting an array of Strings
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:39 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •