How to declare an array in Java? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


How to declare an array in Java?

Jeson84Jeson84 USAPosts: 90Member

Please let me know how to declare an array in Java. I'm starting to lean Java. Please help.



  • NickFNickF USAPosts: 132Member
    edited January 2014

    For primitive types:

    int[] newIntArray = new int[4];

    int[] newIntArray = {1,2,3,4};

    int[] newIntArray = new int[]{1,2,3,4};

    For classes, for example String, it's the same:

    String[] newStringArray = new String[5];

    String[] newStringArray = {"a","b","c","d","e"};

    String[] newStringArray = new String[]{"a","b","c","d","e"};

    Hope I answered your question.

  • GouthamKumarGouthamKumar NellorePosts: 17Member

    The bellow syntax is followed to declare an array.

    Datatype arrayName[] = new Datatype[arraySize];
    int array[] = new int[5];
    float array[] = new int[4];
    char array[] = new int[8];

    Note: Array size should always be an integer.

    Array initalization :
    int array[] = new int array[4];
    array[0] = 1;
    array[1] = 2;
    array[2] = 3;
    array[3] = 4;

    In array[0] 0 represents the index value.
    Second form:
    There is other way of declaring and initializing values to an array.

    int array[] = {1,2,3,.4,5,6};

    For more details on declaration and initialization of arrays please follow the link.

  • manishamanisha Posts: 32Member
    edited June 26

    To declare an array you have to use new keyword, like you create an object in java.

    Declaration of an array of size 10.

    Example: int arr[]=new int[10];
    Array of size 10 is declared. First element will have index 0 so the valid indexes are from 0 to 9. if you try to access arr[10] then it will give you ArrayOutOfBoundsException.

    Initialization of Array:

    After declaration of an array, you can initialize an array using the array variable name and index as follows:

    arr[3]=12; and so on....

    You can combine the declaration and initialization together.

    Declaration and initialization of array:

    int arr[]={1,2,3,4,5,6,7,8,9,10}

    For more Details Refer following link:

Sign In or Register to comment.