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. Good summary, it’s essential to have good knowledge about array in java. Base for many programming tasks.

  2. Rajesh

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

  3. Suresh

    good analysis and explanation for array in java

  4. Rajasekar

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

  5. Gyanendra

    Simple and Good explanation about Java array. Thanks

  6. Tithi

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

  7. tithi

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

  8. Sandeep

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

    Great patience, I must say!!

  9. swati

    precise n important on array in java… great article…

  10. swetha

    Thanks for this complete tutorial.Good analysis and explanation

  11. Anonymous

    ver nice effort to descibe and explain the java array topic

  12. java performance

    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.

  13. java performance

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

  14. Jahnavi

    Good explaination

  15. krishnakanth

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

  16. meher

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

  17. Yevaro

    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.

  18. Ravi

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

  19. Virendra

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

  20. Anonymous

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

  21. Anonymous

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

  22. Anonymous

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

  23. Blackberry Application Developers

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

  24. Anonymous

    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

  25. Ashish

    Really nice tutorial on java array

  26. This is my first blog that is newly created.
    I like your blog website and please keep it up.
    i want to know who are you and what do you do except this blog.
    oh…
    I forgot to write that i am the student of b.tech final year Computer Science branch.
    I like your blog very much. so keep it up for sharing the knowledge.

  27. raisunisa begum

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

  28. Sathish Kumar

    Superb Explanation…. I feel its very useful and thankful

  29. Mukesh

    Really nice tutorial for java arrayl!!!

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

  31. NImeshzalavadiya

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

  32. asadul

    Good But should be very good.

  33. sathya

    simple nd good

  34. srihari

    Very nice blog

  35. James

    Really Nice!! Thumbs up..

  36. sham

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

  37. aditi

    an easy approach to understand concepts of arrays,thanks.

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

  39. Joe

    Guys, thank you for the awesome comments!

  40. ABHAY RAI

    Really nice tutorial on java array

  41. pooja

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

  42. vamsi

    this is the nice tutorial for java beginners.

  43. Balaji

    Really valuable.

  44. neetu mishra

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

  45. Jagdish

    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…

  46. Prashant Zombade

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

  47. Reem

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

  48. Pavan

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

    Kindly answer to this question.

  49. excellent sir i understand very well your blog simply superb

  50. Anonymous

    plz describe the strings n vectors too.thnk u…

  51. ASHISH

    THANKS FOR YOUR SUPPORT

  52. vishnu

    thanks for giving the better explanation

  53. Baskaran

    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?

  54. Baskaran

    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?

  55. bnrao

    Why we use (.length)

    Plz explaine me……

  56. a nice summary about arrays in java

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

  58. rahul

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

  59. vijendra

    what is the default size of array in java

  60. Jyotish

    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

  61. manwinder

    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 …

  62. syamsundarreddy bireddy

    its really very easy to understand n
    thankuuu sir

  63. gowti

    is usefull for this content.

  64. Praveen

    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?

  65. Ajay

    it is very useful for all students

  66. seema

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

  67. Sankar De

    Good for beginners….easy to understand.

  68. vinit

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

  69. thank you sir it’s very good for fresher

  70. AHIR

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

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

    RAJ9992

  72. zubair

    very nice

  73. Abhaya Panda

    what is the default size of array in java

  74. Sunil G

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

  75. Anonymous

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

  76. William

    hi, how do i solve this issue in java?

    My “answer” in the array value is returning an error “cannot convert int to String”….

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Ask extends JApplet implements ActionListener
    {
    private JTextField tboxResponse;
    private final String submit = “Answer”;
    public JLabel lblQuestion;
    private JTextField Result;

    String[] strA = new String[3];
    String[] strQ = new String[3];
    int iQ;

    public void init()
    {

    //get two random numbers between 0 and 9
    int digit1 = ( int ) ( Math.random() * 10 );
    int digit2 = ( int ) ( Math.random() * 10 );
    int answer;

    answer = digit1 * digit2;

    strQ[0] = “Who was the first U.S. President?”;
    strQ[1] = “Who developed the theory of relativity?”;
    strQ[2] = “what is ” + digit1 + ” * ” + digit2 + “?”;
    strA[0] = “Washington”;
    strA[1] = “Einstein”;
    strA[2] = answer;

    // Create user interface
    Container c = getContentPane();

    c.setLayout(new BorderLayout(12,12));
    JLabel gameTitle = new JLabel(“My text game”);
    c.add(gameTitle, BorderLayout.NORTH);
    JPanel workPanel = new JPanel();

    lblQuestion = new JLabel(strQ[0]);

    workPanel.add(lblQuestion);
    tboxResponse = new JTextField(16);
    workPanel.add(tboxResponse);

    Result = new JTextField(16);
    Result.setEditable( false );
    c.add(Result);
    c.add(workPanel, BorderLayout.CENTER);

    // create buttons
    JPanel pnlButtons = new JPanel();
    JButton btnSubmit = new JButton(submit);
    btnSubmit.addActionListener(this);
    pnlButtons.add(btnSubmit);
    c.add(pnlButtons, BorderLayout.SOUTH);

    // add buttons panel to user interface
    c.add(pnlButtons, BorderLayout.SOUTH);

    setSize (400,300);

    }

    public void actionPerformed(ActionEvent e)

    {

    String command = e.getActionCommand();

    if ( strA[iQ].equals ( tboxResponse.getText() ) )

    {
    tboxResponse.setText( “That is correct!” );
    }

    else

    {
    tboxResponse.setText( “That is incorrect!” );
    }

    iQ = iQ + 1;
    lblQuestion.setText(strQ[iQ]);

    }

    }

  77. gopi

    it’s fabulos…… helped me alot

  78. nithish

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

  79. Jonali Chatterjee

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

  80. Raghava

    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

  81. Guneet

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

  82. very nice keep it up!!!

  83. Manohar Kumar

    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);

  84. Nice stuff Dear….
    also Learn about Arrays click on below link
    W3STutorial

  85. sudha

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

  86. i like that you mentioned default values in array GOOD

Your Comment