Java Array

When you need to store same ‘type’ of data that can be logically grouped together, then you can go for java array.

For example, imagine if you had to store the list of countries in individual java variables and manipulate them. You will have more than hundred variables to manage. Can’t imagine, it would be tedious in any language. Have you ever seen a decent size application programmed without arrays?

In this article you will not find nothing new about java array. Just the same old theory to refresh and I will try to be comprehensive. If you expect some surprise or hidden thing from java, please ALT-F4.

java array logical view

Array is one among the many beautiful things you have in a programming language. Easy to iterate, easy to store and retrieve using their integer index. In java, nobody can deny using an array I challenge. I know you all started with public static void main(?). The argument for the main method is an array.

In java arrays are objects. All methods of an Object can be invoked on an array. Arrays are stored in heap memory.

java array - physical view

Ads by Google

Though we view the array as cells of values, internally they are cells of variables. A java array is a group of variables referenced by a common name. Those variables are just references to a address and will not have a name. These are called the ‘components’ of a java array. All the components must be of same type and that is called as ‘component type’ of that java array.

Java Array Declaration

int []marks;

or

int marks[];

Java Array Instantiation

marks = new int[5];

5 inside the square bracket says that you are going to store five values and is the size of the array ‘n’. When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1′. An array index is always a whole number and it can be a int, short, byte, or char.

Once an array is instantiated, it size cannot be changed. Its size can be accessed by using the length field like .length Its a java final instance field.

All java arrays implements Cloneable and Serializable.

Java array initialization and instantiation together

int marks[] = {98, 95, 91, 93, 97};

ArrayIndexOutOfBoundsException

One popular exception for java beginners is ArrayIndexOutOfBoundsException. You get ArrayIndexOutOfBoundsException when you access an array with an illegal index, that is with a negative number or with a number greater than or equal to its size. This stands second next to NullPointerException in java for popularity.

Java Array Default Values

After you instantiate an array, default values are automatically assigned to it in the following manner.

  • byte – default value is zero
  • short – default value is zero
  • int – default value is zero
  • long – default value is zero, 0L.
  • float – default value is zero, 0.0f.
  • double – default value is zero, 0.0d.
  • char – default value is null, ‘\u0000′.
  • boolean – default value is false.
  • reference types – default value is null.

Notice in the above list, the primitives and reference types are treated differently. One popular cause of NullPointerException is accessing a null from a java array.

Iterating a Java Array

public class IterateJavaArray {
	public static void main(String args[]) {
		int marks[] = {98, 95, 91, 93, 97};
		//java array iteration using enhanced for loop
		for (int value : marks){
			System.out.println(value);
		}
	}
}

In language C, array of characters is a String but this is not the case in java arrays. But the same behaviour is implemented as a StringBuffer wherein the contents are mutable.

ArrayStoreException – When you try to store a non-compatible value in a java array you get a ArrayStoreException.

Multidimensional Arrays

When a component type itself is a array type, then it is a multidimensional array. Though you can have multiple dimension nested to n level, the final dimension should be a basic type of primitive or an Object.

int[] marks, fruits, matrix[];

In the above code, matrix is a multidimensional array. You have to be careful in this type of java array declaration.

Internally multidimensional java arrays are treated as arrays of arrays. Rows and columns in multidimensional java array are completely logical and depends on the way you interpret it.

Note: A clone of a java multidimensional array will result in a shallow copy.

Iterate a java multidimensional array

Following example source code illustrates on how to assign values and iterate a multidimensional java array.

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

		int sudoku[][] = { { 2, 1, 3 }, { 1, 3, 2 }, { 3, 2, 1 } };

		for (int row = 0; row < sudoku.length; row++) {
			for (int col = 0; col < sudoku[row].length; col++) {
				int value = sudoku[row][col];
				System.out.print(value);
			}
			System.out.println();
		}
	}
}

Sort a Java array

java api Arrays contains static methods for sorting. It is a best practice to use them always to sort an array.

import java.util.Arrays;

public class ArraySort {
	public static void main(String args[]) {
		int marks[] = { 98, 95, 91, 93, 97 };
		System.out.println("Before sorting: " + Arrays.toString(marks));
		Arrays.sort(marks);
		System.out.println("After sorting: " + Arrays.toString(marks));
	}
}
//Before sorting: [98, 95, 91, 93, 97]
//After sorting: [91, 93, 95, 97, 98]

Copy a Java array

You can use the following options to copy a java array:

  • As illustrated above you can use the util calls Arrays. It contains copyOf method for different java types.
  • The most used class by a java beginner 'System' has a static method to copy an array.
  • Using its clone method you can copy a java array. If the java array is multidimensional, it will be a shallow copy.
  • Write your own for loop iterating through the java array and copy elements yourself. (least preferred)

This Core Java tutorial was added on 31/01/2011.

«

»

Comments on "Java Array"

  1. Anas vn says:

    i like that you mentioned default values in array GOOD

  2. […] data area is used to store objects of classes and arrays. Heap memory is common and shared across multiple threads. This is where the garbage collector […]

  3. Anonymous says:

    nice

  4. sudha says:

    nice explanation………..
    the index value is given by three valus.so how many index value are possible for java………..?plz rly me sir…

  5. Manohar Kumar says:

    Hi Sir,
    I Want solution for the below question. Could you please send me solution.

    Question: We are given an array of 2n integers wherein each pair in this array of integers represents the year of birth and the year of death of a dinosaurs respectively. The range of valid years we want to consider is [-100000 to 2005]. For example, if the input was:

    -80000 -79950 20 70 22 60 58 65 1950 2004

    it would mean that the first dinosaur had a birth year of –80000 and an year of death of –79950 respectively. Similarly the second dinosaur lived from 20 to 70 and so on and so forth.

    We would like to know the largest number of dinosaurs that were ever alive at one time. Write a method to compute this, given the above array of 2n integers.

    using method
    public int findMaxdinosaur (int[] years);

  6. kajendra says:

    very nice keep it up!!!

  7. Guneet says:

    Its very good blog ….helped me a lot as a fresher in java

  8. Raghava says:

    Explanation was Good, but i have doubt on iteration of logic.
    exp :

    int Arr [] = {49, 50, 60, 45, 75};

    for(int i=0; i<5; i++)
    {
    System.out.println(Arr[i]);
    }

    in the above exp how it will find the Arr[i], directly.
    Declaration is ok and Initialization also ok but in print method how it is going to find [i] here.
    can you please explain for me

  9. Jonali Chatterjee says:

    Very lucidly explained…many sites just state the fact rather providing a complete simple code.Thanks to you for your sincere efforts,vision and knowing what starters like us are really looking for..!!

  10. nithish says:

    Thanks a lot :-)
    sudoku prog’m is lovely :-)

  11. gopi says:

    it’s fabulos…… helped me alot

  12. Anonymous says:

    even i have prepared some good articles about java i have to post it.very soon every java lovers will see change in java.

  13. Sunil G says:

    Very nice with explanation. Please cover some more chapters on Java.

  14. Abhaya Panda says:

    what is the default size of array in java

  15. zubair says:

    very nice

  16. RAJ9992 says:

    Small Doudbt what is the need of Arrays concept in java
    collections concepts shows each and every scenario regarding Arrays …..

    RAJ9992

  17. AHIR says:

    plz tell me how to implement values by user through at run time in matrix ????

  18. Amardeep says:

    thank you sir it’s very good for fresher

  19. vinit says:

    tell me about new technique in array
    who is easy to learn or implement

  20. Sankar De says:

    Good for beginners….easy to understand.

  21. seema says:

    thanks sir. thank u very much. this is very helpful :-)

  22. Ajay says:

    it is very useful for all students

  23. Praveen says:

    Hi Joe,
    Could you please provide the internal implementation of ArrayList. As we know, ArrayList internally uses Array. Array stores the addresses consecutively in physical memory but in case of ArrayList, we can add any number objects at any time. How is it going to work internally in terms of storage?

  24. gowti says:

    is usefull for this content.

  25. syamsundarreddy bireddy says:

    its really very easy to understand n
    thankuuu sir

  26. manwinder says:

    Hey sir!!! u have helped me a lott in understanding arrays….thankx a lottt …plz continue ur blog and tell us more on error handling …

  27. Jyotish says:

    to creat an object..we write
    classname variablename=new classname();
    where , classname is data type
    varname is object ref holder
    new is keyword to allocate memory & return address
    classname() is constructor to make an object & to initialze instance variable
    but in Array creation we write
    datatype []var_nam=new datatype[];
    but my que is in creation why there is no constructor & how witout it array object is created ????????

    please reply me sir..i m bother about this

  28. vijendra says:

    what is the default size of array in java

  29. rahul says:

    great . . i found it very useful and easy to understand…keep going :) god bless you

  30. ankit srivastava says:

    hi Baskaran,defintly v can create dynamic array in java by using vectors,it can store objects of any number and any type.

  31. ankit srivastava says:

    a nice summary about arrays in java

  32. bnrao says:

    Why we use (.length)

    Plz explaine me……

  33. Baskaran says:

    Hi Joe, I have a question, can we create a dynamic array?, I was asked this question in an interview? I stood in the point that we cant create but we can use ArrayList instead, but the interviewer said it is possible, do you have answer for this?

  34. Baskaran says:

    Hi I have a question, can we create a dynamic array?, I was asked this question in an interview? I stood in the point that we cant create but we can use ArrayList instead, but the interviewer said it is possible, do you have answer for this?

  35. vishnu says:

    thanks for giving the better explanation

  36. [...] System – is a final class and cannot be instantiated. Therefore all its memebers (fields and methods) will be static and we understand that it is an utility class. As per javadoc, “…Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array…” [...]

  37. ASHISH says:

    THANKS FOR YOUR SUPPORT

  38. Anonymous says:

    plz describe the strings n vectors too.thnk u…

  39. rajesh says:

    excellent sir i understand very well your blog simply superb

  40. Pavan says:

    As you said, In Java arrays are objects..
    For which class the array object is created?

    Kindly answer to this question.

  41. Reem says:

    Thank you,
    you give us good explination.

    I want to be good programmer.but I have problem when write programe.

    when write programe using Array the out put show me message like..ArrayIndexOutOfBoundsException
    Can you help me please.
    Thanks,,

  42. Prashant Zombade says:

    @Jagdish,
    1. Yes, it is the JVM who creates array objects.
    2. JVM uses java.lang.Object class to create array objects.
    3. Object class from java.lang package is the immediate super class of any array objects.
    4. No it does not implement any interface.

    Also be informed that irrespective of the array size and dimensions only one array object is created on behalf of array.

    i.e int[] arr = {1,2,3,4,5};
    Above code creates only on object named arr in the heap memory.

    String strArr = {“ONE”,”TWO”};
    Three objects get created in above code.
    1. strArry 2. “ONE” 3. “TWO”

    Hope this solves your doubts.

  43. Jagdish says:

    Hi Joe,
    arrays are objects in java.To creats an object we need the corresonding class. so
    *Who creats array object ,is it JVM ?
    *if JVM creats then which class it uses ?
    * who is the immediate super class of array object ?
    *is it implementing any interface ?

    please explain it…

  44. neetu mishra says:

    this is very good n easily understandble defination of array ,,,,thanx a lot——-

  45. Balaji says:

    Really valuable.

  46. vamsi says:

    this is the nice tutorial for java beginners.

  47. pooja says:

    thanks for writing this article..
    it is very useful in array programming :)

  48. ABHAY RAI says:

    Really nice tutorial on java array

  49. Joe says:

    Guys, thank you for the awesome comments!

  50. aditi says:

    an easy approach to understand concepts of arrays,thanks.

  51. aditi says:

    A wonderful effort to solve our problems thanks for ur guidance sir.

  52. harsha says:

    marvellous

  53. muniraj says:

    good

  54. sham says:

    Nice.. tutorial for java array.. really helped lot… for the beginners..

  55. James says:

    Really Nice!! Thumbs up..

  56. srihari says:

    Very nice blog

  57. sathya says:

    simple nd good

  58. asadul says:

    Good But should be very good.

  59. NImeshzalavadiya says:

    very nice tutorial on array in java
    it is very helpfull to other people

  60. gaurav chaudhary says:

    so cool article dost…I love Java ..I also used to write about java technologies.
    Just now i wrote some articles on java concepts and java programing test..

    I want to come my blog and share some information

    Thanks

  61. Mukesh says:

    Really nice tutorial for java arrayl!!!

  62. Sathish Kumar says:

    Superb Explanation…. I feel its very useful and thankful

  63. raisunisa begum says:

    Thanks for the information provided..its gud and easily understandable…but i got one doubt why the size of the array can’t be changed..??? any reason? or any rule?you mentioned that size of an array can’t be changed but why? please tell the answer…..

  64. Ashish says:

    Really nice tutorial on java array

  65. Anonymous says:

    just to keep a log of stuff that I come across in java. I do this with lot of passion and you may find interesting things around …more about me and blog
    © javapapers.com

  66. Blackberry Application Developers says:

    Nice blog…Well presented..looking forward for more blogs about java concepts..

  67. Anonymous says:

    why the java index starts from 0??
    tell us what is the fact.

  68. Anonymous says:

    why the java index starts from 0??
    tell us what is the fact.

  69. Anonymous says:

    why java index starts from 0 in java array??
    tell us what is the fact.

  70. Virendra says:

    Joseph you rock…
    best article for java array…
    Keep it up frnd..

  71. Ravi says:

    Good explanation, but I didn’t not quite understand the physical view array part.
    Overall very well written.

  72. Yevaro says:

    first, I appreciate your attitude behind writing this article – sharing your knowledge with others. though it sounds like English is not your first language, I must say that you have tried your best to make it simple. no wonder it had a million hit.

  73. meher says:

    Nice blog….its very useful and easy to understand…… thankz

  74. krishnakanth says:

    its good can be easily understood….
    pls keep it up ..

  75. Jahnavi says:

    Good explaination

  76. java performance says:

    thanks, i too struggle with the java array syntax. these examples are very helpful.

  77. java performance says:

    Thanks for these examples on array in java! Showing different ways to create string arrays is very helpful, as is the Java 5 for loop syntax example.

  78. Anonymous says:

    ver nice effort to descibe and explain the java array topic

  79. swetha says:

    Thanks for this complete tutorial.Good analysis and explanation

  80. swati says:

    precise n important on array in java… great article…

  81. Sandeep says:

    That’s very well documented. java array can’t be explained in more detail

    Great patience, I must say!!

  82. tithi says:

    Sir,can u plz jst provide me a little more brief idea wth some examples of JAVA ACCESS MODIFIERS…
    thanx & regards

  83. Tithi says:

    nice blog Sir…it’s so easy to understand for d beginners like me…i liked ur ACCESS MODIFIERS article 2….it helps me a lot….
    thnx….

  84. Gyanendra says:

    Simple and Good explanation about Java array. Thanks

  85. Rajasekar says:

    Great tutorial for java array. It’s really very nice and easy to understand compare then other materials.

  86. Suresh says:

    good analysis and explanation for array in java

  87. Rajesh says:

    thanks for this complete tutorial on java array.. easy to understand than any book

  88. Arttu says:

    Good summary, it’s essential to have good knowledge about array in java. Base for many programming tasks.

Your Comment