Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Introduction to Arrays in Java

This tutorial covers creating, accessing, initializing, inserting, searching and deleting arrays and their elements in Java. Examples are given for each of these actions to aid the reader in getting a hands-on experience.

On Saturday, March 1st 2008 at 09:56 PM
By Louis Fernandez (View Profile)
*****   (Rated 4.3 with 11 votes)
Contextual Ads
More Java Resources
Advertisement

Creating an Array

There are two kinds of data in Java: primitive types (such as int and double) and objects. In many programming languages (even object-oriented ones such as C++), arrays are primitive types, but in Java they’re treated as objects. Accordingly, you must use the new operator to create an array:

int[] intArray; // defines a reference to an array
intArray = new int[100]; // creates the array, and sets intArray to refer to it

Or you can use the equivalent single-statement approach:

int[] intArray = new int[100];

The [] operator is the sign to the compiler we’re naming an array object and not an ordinary variable. You can also use an alternative syntax for this operator, placing it after the name instead of the type:

int intArray[] = new int[100]; // alternative syntax

However, placing the [] after the int makes it clear that the [] is part of the type, not the name.

Because an array is an object, its name - intArray in the preceding code - is a reference to an array; it’s not the array itself. The array is stored at an address elsewhere in memory, and intArray holds only this address.

Arrays have a length field, which you can use to find the size (the number of elements) of an array:

int arrayLength = intArray.length; // find array size

As in most programming languages, you can’t change the size of an array after it’s been created.

 

Accessing Array Elements

Array elements are accessed using an index number in square brackets. This is similar to how other languages work:

temp = intArray[3]; // get contents of fourth element of array
intArray[7] = 66; // insert 66 into the eighth cell

Remember that in Java, as in C and C++, the first element is numbered 0, so that the indices in an array of 10 elements run from 0 to 9.

If you use an index that’s less than 0 or greater than the size of the array less 1, you’ll get the Array Index Out of Bounds runtime error.

 

Initialization

Unless you specify otherwise, an array of integers is automatically initialized to 0 when it’s created. Unlike C++, this is true even of arrays defined within a method (function). Say you create an array of objects like this:

autoData[] carArray = new autoData[4000];

Until the array elements are given explicit values, they contain the special null object. If you attempt to access an array element that contains null, you’ll get the runtime error Null Pointer Assignment. The moral is to make sure you assign something to an element before attempting to access it.

You can initialize an array of a primitive type to something besides 0 using this syntax:

int[] intArray = { 0, 3, 6, 9, 12, 15, 18, 21, 24, 27 };

Perhaps surprisingly, this single statement takes the place of both the reference declaration and the use of new to create the array. The numbers within the curly brackets are called the initialization list. The size of the array is determined by the number of values in this list.

 

An Array Example

Let’s look at some example programs that show how an array can be used. We’ll start with an old-fashioned procedural version and then show the equivalent objectoriented approach. The code below shows the old-fashioned version, called array.java:

// array.java
// demonstrates Java arrays
// to run this program: C>java arrayApp
////////////////////////////////////////////////////////////////

class ArrayApp
{
   public static void main(String[] args)
   {
      long[] arr; // reference to array
      arr = new long[100]; // make array
      int nElems = 0; // number of items
      int j; // loop counter
      long searchKey; // key of item to search for
      //--------------------------------------------------------------
      arr[0] = 77; // insert 10 items
      arr[1] = 99;
      arr[2] = 44;
      arr[3] = 55;
      arr[4] = 22;
      arr[5] = 88;
      arr[6] = 11;
      arr[7] = 00;
      arr[8] = 66;
      arr[9] = 33;
      nElems = 10; // now 10 items in array
      //--------------------------------------------------------------
      for(j=0; j<nElems; j++) // display items
      System.out.print(arr[j] + “ “);
      System.out.println(“”);
      //--------------------------------------------------------------
      searchKey = 66; // find item with key 66
      for(j=0; j<nElems; j++) // for each element,
      if(arr[j] == searchKey) // found item?
      break; // yes, exit before end
      if(j == nElems) // at the end?
      System.out.println(“Can’t find “ + searchKey); // yes
      else
      System.out.println(“Found “ + searchKey); // no
      //--------------------------------------------------------------
      searchKey = 55; // delete item with key 55
      for(j=0; j<nElems; j++) // look for it
      if(arr[j] == searchKey)
      break;
      for(int k=j; k<nElems-1; k++) // move higher ones down
      arr[k] = arr[k+1];
      nElems--; // decrement size
      //--------------------------------------------------------------
      for(j=0; j<nElems; j++) // display items
         System.out.print( arr[j] + “ “);
      System.out.println(“”);
   } // end main()
} // end class ArrayApp

In this program, we create an array called arr, place 10 data items (kids’ numbers) in it, search for the item with value 66 (the shortstop, Louisa), display all the items, remove the item with value 55 (Freddy, who had a dentist appointment), and then display the remaining 9 items. The output of the program looks like this:

77 99 44 55 22 88 11 0 66 33
Found 66
77 99 44 22 88 11 0 66 33

The data we’re storing in this array is type long. We use long to make it clearer that this is data; type int is used for index values. We’ve chosen a primitive type to simplify the coding. Generally, the items stored in a data structure consist of several fields, so they are represented by objects rather than primitive types. We’ll see such an example toward the end of this chapter.

 

Insertion

Inserting an item into the array is easy; we use the normal array syntax:

arr[0] = 77;

We also keep track of how many items we’ve inserted into the array with the nElems variable.

 

Searching

The searchKey variable holds the value we’re looking for. To search for an item, we step through the array, comparing searchKey with each element. If the loop variable j reaches the last occupied cell with no match being found, the value isn’t in the array. Appropriate messages are displayed: Found 66 or Can’t find 27.

 

Deletion

Deletion begins with a search for the specified item. For simplicity, we assume (perhaps rashly) that the item is present. When we find it, we move all the items with higher index values down one element to fill in the “hole” left by the deleted element, and we decrement nElems. In a real program, we would also take appropriate action if the item to be deleted could not be found.

 

Display

Displaying all the elements is straightforward: We step through the array, accessing each one with arr[j] and displaying it.

Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by seno on Tuesday, June 10th 2008 at 01:30 PM

to complex of an example

by princess_18 on Friday, August 8th 2008 at 01:51 PM

ur tutorial is quite amazing but as of now I'm really in need of help about my activity at school. Its about displaying the inputted values and arranging it in an ascending order..please do help me! it will be passed 2morow.tnx. God Bless.

by misrena on Tuesday, September 9th 2008 at 11:18 PM

How to insert item 60 between 44 and 22? So the output program will like this:
77 99 44 22 88 11 0 66 33 (output when arr[3]=55 removed;
77 99 44 60 22 88 11 0 66 33 (insert arr[3]=60;

Thanks.

by venkatesan.R on Thursday, October 30th 2008 at 05:21 AM

Hello,sir
i take two array values,one for Odd Numbers another Even Number.But print the values sequence order.
For Example a[]={1,3,5,7,9}
b[]={2,4,6,8}
this values print for output in this manner sir,
OutPut:
1
2
3
4
5
6
7
8
9
plz i want soultion.send my mail address sir

by Slim on Tuesday, December 9th 2008 at 11:07 PM

1
3
4

if i want to insert 2 how?help me

by Litty Joy Galabo on Friday, July 3rd 2009 at 06:30 AM

Hi sir..Please help me with my project..it is a program that would input 10 integers and would distinguish whether the inputted number is odd or even..and will print the highest and lowest inputted number...thanks in advance sir...please do help me with this project...just send it through my email...galabolittyjoy@yahoo.com...

by johnny depp on Thursday, November 5th 2009 at 05:36 AM

very helpfull tutorial.. thanks mate

by angel on Tuesday, December 8th 2009 at 02:20 PM

Create a JavaScript calculator to that takes two numbers and display the
arithmetic operation

iam from ksa and a did know how to solve this?????
can someone help me.........
thanks alot

by Jean Ribon on Wednesday, March 10th 2010 at 10:27 AM

Sir, please help me with my project in programming.we had a case study about binary to decimal,converting odd to even number.we have to depends it in my proffesor.binary to decimal in java programming...thank you sir. hope you can help me...

by subbulakshmi on Friday, March 26th 2010 at 03:25 AM

Hello,sir
i take two array values,one for Odd Numbers another Even Number.But print the values sequence order.
For Example a[]={1,3,5,7,9}
b[]={2,4,6,8}
this values print for output in this manner sir,
OutPut:
1
2
3
4
5
6
7
8
9
plz i want soultion.send my mail address sir

by Rey Gamboa on Monday, April 5th 2010 at 09:39 PM

Sir please Help me with my

by subbulakshmi on Tuesday, April 6th 2010 at 12:52 AM

thanku sir.

by subbulakshmi on Tuesday, April 6th 2010 at 12:52 AM

thank u sir.

by Rey Gamboa on Tuesday, April 6th 2010 at 09:12 PM

sir please help me with my program..
what is the best java langyages i have to use at this problem..
Array1

create an integer array with 5 elements.

store INPUTED data in it.

Display the stored data.

---
Array2

create a character array with 5 elements.

store INPUTED data in it.

Display the stored data.

---
Array3

create a string array with 5 elements.

store INPUTED data in it.

Display the stored data.

thank you sir

by Jennifer on Saturday, July 17th 2010 at 08:26 PM

I have to set up an array where the user gets to choose 5 numbers of their choice and I need to set up an array that reverses the order of the numbers the user has choosen

by Dhruv on Tuesday, August 3rd 2010 at 11:00 PM

hello sir dis is dhruv
can u plz send me the solution 2 dis program on my id

find the highest and the lowest temperatures out of ten cities and print the highest and lowest temperatues out of the lot along with the corresponding cities

by surendra singh jadon on Wednesday, August 4th 2010 at 03:41 AM

sir i want to know how can i write a program which
write first insert your 7 value=> and then the value is insert in our declayered array[6].
plese send on my address the logic of this.
ok.

by surendra singh jadon on Wednesday, August 4th 2010 at 03:41 AM

sir i want to know how can i write a program which
write first insert your 7 value=> and then the value is insert in our declayered array[6].
plese send on my address the logic of this.
ok.

by surendra singh jadon on Wednesday, August 4th 2010 at 03:41 AM

sir i want to know how can i write a program which
write first insert your 7 value=> and then the value is insert in our declayered array[6].
plese send on my address the logic of this.
ok.

by surendra singh jadon on Wednesday, August 4th 2010 at 03:41 AM

sir i want to know how can i write a program which
write first insert your 7 value=> and then the value is insert in our declayered array[6].
plese send on my address the logic of this.
ok.

by surendra singh jadon on Wednesday, August 4th 2010 at 03:41 AM

sir i want to know how can i write a program which
write first insert your 7 value=> and then the value is insert in our declayered array[6].
plese send on my address the logic of this.
ok.

by surendra singh jadon on Wednesday, August 4th 2010 at 03:41 AM

sir i want to know how can i write a program which
write first insert your 7 value=> and then the value is insert in our declayered array[6].
plese send on my address the logic of this.
ok.


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials

Sort an Array of Strings in Reverse Order

On Saturday, February 2nd 2008 at 12:51 AM by Louis Fernandez in Java

Parsing Character Delimited Files into Arrays

On Wednesday, September 19th 2007 at 10:52 PM by Andrew Pociu in PHP

Introduction to arrays, sorting arrays

On Saturday, July 30th 2005 at 12:55 PM by Andrew Pociu in JavaScript

Jagged arrays

On Sunday, July 25th 2004 at 11:34 PM by Andrew Pociu in C#


Comment Related Source Code
There is no related source code.

Jobs Java Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources