Results 1 to 4 of 4

Thread: Arrays in Java

  1. #1
    hiranya is offline Member
    Join Date
    Jun 2007
    Location
    Colombo, Sri Lanka
    Posts
    32
    Rep Power
    0

    Default Arrays in Java

    I'm a bit confused about the way how arrays are declared and used in Java.:confused: Please enlighten me on how to declare and utilize arrays in Java.

  2. #2
    shanePreater is offline Member
    Join Date
    Jul 2007
    Location
    England, Bath
    Posts
    47
    Rep Power
    0

    Default

    Arrays are declared using the [] notation so to declare an array of String objects you would do the following:
    Java Code:
    String[] stringArray;
    Now if you want to actually create the instance of the String array then you need to specify the size within the []'s:

    Java Code:
    String[] stringArray = new String[7];
    This then gives you an empty container to place your String objects into the array:
    Java Code:
    stringArray[0] = "First";
    etc etc.

    Moving to something a bit more complex like your own classes the same prinicipal applies so if we had a class Bob which is constructed with a pair of string arguments it would be something like this:

    Java Code:
    Bob[] bobs = new Bob[7];
    bobs[0] = new Bob("Some", "Data");
    bobs[1] = otherBobVariable;
    This is perfectly fine for fixed sized arrays but you may be better off using a collection instead and then using the collections toArray() methods to create your array when you need it.

    Hope this helps.

  3. #3
    Seemster is offline Member
    Join Date
    Jul 2007
    Posts
    55
    Rep Power
    0

    Default

    I personally use ArrayList instead of Arrays. You can use a helper method to convert the arraylist to an array. That way you don't have to set the initial or default size of the array. It also prevents OutofBound exceptions.

  4. #4
    Swamipsn is offline Member
    Join Date
    Jul 2007
    Posts
    74
    Rep Power
    0

    Default

    Strong a[]="hai;
    String n = new String[];
    pls refer online tutorial for many types of arra declarations in java

Similar Threads

  1. Arrays
    By bunbun in forum New To Java
    Replies: 1
    Last Post: 04-09-2008, 03:24 AM
  2. new to arrays
    By jimJohnson in forum New To Java
    Replies: 1
    Last Post: 04-08-2008, 03:45 PM
  3. Help needed with java arrays code
    By d24706 in forum New To Java
    Replies: 2
    Last Post: 03-07-2008, 02:11 AM
  4. 2D-Arrays
    By kbyrne in forum New To Java
    Replies: 1
    Last Post: 02-07-2008, 11:08 PM
  5. arrays help
    By Warren in forum New To Java
    Replies: 6
    Last Post: 11-23-2007, 08:23 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
  •