Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Spring Framework | Web Services | BioInformatics | Java Server Faces | Jboss 3.0 tutorial | Hibernate 3.0 | XML
 
 
Hot Web Programming Job

 

Tutorial Categories: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML


 

Java Tutorials

Core Java
JSP
Servlet
JDBC
Hibernate
Struts 1
Struts 2
JSF
Spring
J2EE
J2ME
Web Services
Ajax
Dojo
MySQL
Latest Comments
Contents are not d
Please Use JAVA no
hidden tag in orku
Getting good knowl
Why the output on
  All Comments...
 

 

 
Struts Tutorials
*Stuts TOC
*Apache Struts Introduction
* Struts Controller
* Struts Action Class
* Struts ActionFrom Class
* Using Struts HTML Tags
*Struts Validator Framework    
*Client Side Address Validation    
*Struts Tiles
*tiles-defs.xml
*Struts DynaActionForm
*Struts File Upload
*Struts DataSource
*AGGREGATING ACTIONS
*Internationalization
Struts Resources
*Struts Books
*Struts Articles
*Struts Frameworks
*Struts IDE
*Struts Alternative
*Struts Links
*Struts Presentations
*Struts Projects
*Struts Software
*Struts Reference
*Struts Resources
*Other Struts Tutorial
Visit Forum! Post Questions!
Jobs At RoseIndia.net!

Have tutorials?
Add your tutorial to our Java Resource and get tons of hits.

We offer free hosting for your tutorials. and exposure for thousands of readers. drop a mail
roseindia_net@yahoo.com
 
   

 
Join For Newsletter

Powered by groups.yahoo.com
Visit Group! Post Questions!

Java Notes

Arrays

[an error occurred while processing this directive]

Java arrays are similar to ideas in mathematics

An array can store many similar values in memory. Each value can be accessed by specifying a subscript or index. "Array" in Java means approximately the same thing as array, matrix, or vector does in math.

Unlike math, you must declare the array and allocate a fixed amount of memory for it.

Declaring an array

An array variable is like other variables -- you must declare it, which means you must declare the type of elements that are in an array. All elements must be the same type. Write the element type name, then "[]", then the name of the array variable. The declaration allocates only enough space for a reference to an array (typically 4 bytes), but doesn't create the actual array object.

String[]  args;   // args is an array of Strings
int[]     scores; // scores is an array of ints
JButton[] bs;     // bs is an array of JButtons

No size in declaration. Unlike some languages, never put the size of the array in the declaration because an array declaration specifies only the element type and the variable name.

Allocate an array object with new

Create an array using new. This example creates an array of 100 int elements, from a[0] to a[99].

int[] a;           // Declare a to be an array of ints
a = new int[100];  // Allocate an array of 100 ints

These are often combined in one line.

int[] a = new int[100];  // Declare and allocate.

Subscripts

Subscripts are enclosed in square brackets []. xi in mathematics is x[i] in Java, and is pronounced "x-sub-i".

Subscript ranges always start at zero because Java came largely from C++, which had a good reason for using zero (pointer arithmetic on arrays). It isn't the way that humans normally count; you'll just have to live with it.

Java always checks subscript legality to be sure the subscript is >= 0, and less than the number of elements in the array. If the subscript is outside this range, Java throws ArrayIndexOutOfBoundsException. This is far superior to the behavior of C and C++, which allow out of range references. Consequently, Java programs are far less susceptible to bugs and security flaws than C/C++ programs.

Length of an array

Each array has a constant (final) instance variable that has its length. You can find out how many elements an array can hold by writing the array name followed by .length. In the previous example, a.length would be 100. Remember that this is the number of elements in the array, one more than the maximum subscript.

Java idiom for looping over an array

The most common use of .length is in a for loop test condition. For example, the variable i will go over the entire range of subscripts of the array a.

for (int i=0; i < a.length; i++) { 
    . . .
}

If you only need to reference the value of each of the elements, you can use the somewhat simpler Java 5 for loop, which keeps track of the index and assigns successive values to a variable (v in this example).

for (int v : a) { 
    . . .
}

Example Version 1 -- Adding all elements of an array

These statements create an array and put 1000 random values in it. The second loop adds all 1000 elements. It would have been better to add them in the first loop, but writing it this way allows two examples of loops.

int[] a;           // Declare an array of ints
a = new int[1000]; // Create an array of 1000 ints.

//... Assign random values to each element.
for (int i=0; i<a.length(); i++) {
    a[i] = (int)(Math.random() * 100000);  // Random number 0-99999
}

//... Add all values in the array.
int sum = 0;           // Start the total sum at 0.
for (int i=0; i<a.length; i++) {
    sum = sum + a[i];  // Add the next element to the total
}

Example Version 2 -- Adding all elements of an array in Java 5

This is the the same as above, but uses the Java 5 "for each" loop to do the sum, which frees you from using an index if you simply need to get all successive values. This kind of loop only gets the values, so it couldn't have been used to set the values in the first loop above.

. . .
int sum = 0;        // Start the total sum at 0.
for (int v : a) {
    sum = sum + v;  // Add the next element to the total
}

Initial array element values -- zero/null/false

When an array is allocated (with new), all elements are set to an initial value. The initial value is 0 if the element type is numeric (int, float, ...), false for boolean, and null for all object types.

Array Initialization

When you declare an array, you can can also allocate a preinitialized array object in the same statement. In this case, do not give the array size because Java counts the number of values to determine the size. For example,

// Java 1.0 style -- shorter, but can be used ONLY IN DECLARATIONS
String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

Array variables are references to arrays

When you declare an array variable, Java reserves only enough memory for a reference (Java's name for an address or pointer) to an array object. References typically require only 4 bytes. When an array object is created with new, a reference is returned, and that reference can then be assigned to a variable. When you assign one array variable to another, only the reference is copied. For example,

int[] a = new int[] {100, 99, 98};
int[] b;
// "a" points to an array, and "b" doesn't point to anything
b = a;      // Now b referes to the SAME array as "a"
b[1] = 0;   // Also changes a[1] because a and b refer to the same array.
// Both a and b refer to same array with value {100, 0, 98}

Intermediate Arrays

Anonymous arrays

Java 2 added anonymous arrays, which allow you to create a new array of values anywhere in the program, not just in an initialization in a declaration.
// This anonymous array style can also be used in other statements.
String[] days = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};
You can also use anonymous array syntax in other parts of the program. For example,
// Outside a declaration you can make this assignment.
x = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};
You must be careful not to create these anonymous arrays in a loop or as local variables because each use of new will create another array.

Dynamic allocation

Because arrays are allocated dynamically, the initialization values may arbitrary expresssions. For example, this call creates two new arrays to pass as parameters to drawPolygon.

g.drawPolygon(new int[] {n, n+45, 188}, new int[] {y/2, y*2, y}, 3);

C-style array declarations

Java also allows you to write the square brackets after the variable name, instead of after the type. This is how you write array declarations in C, but is not a good style for Java. C declaration syntax can get very ugly with part of the declaration before the variable, and part after. Java has a much nicer style where all type information can be written together without the use of a variable, and there are times when only the Java notation is possible to use.
   int[] a;   // Java style -- good
   int a[];   // C style -- legal, but not Java style

Converting between arrays and Collections data structures

[TO DO]

Common array problems

Some common array programming mistakes are:
  • Forgetting that array subscripts start with zero.
  • Writing a.length() instead of a.length. The length() method is used with Strings, not arrays.
  • [an error occurred while processing this directive] Declaring an array with a size. Eg, int[100] a; instead of int[] a = new int[100];.

Library methods for arrays

Static methods for manipulating arrays are available in the java.util.Arrays class.

Arrays.asList() Returns a List based on the array.
Arrays.toString()Returns a readable form of the array.
Arrays.binarySearch()Performs binary serach of a sorted array.
Arrays.equals Compares two arrays for equality.
Arrays.fill() Fills entire array or subrange with a value.
Arrays.sort() Sorts an array.

In addition there is System.arrayCopy() method.

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

1 comments so far (
post your own) View All Comments Latest 10 Comments:

It's helpful me to improve my knowledge

Posted by vichithra on Wednesday, 12.3.08 @ 08:07am | #82329

  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification

Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.