Home

      Hosting      Domains       Support       Contacts

Java Tutorial Home 2 3 4 5 6 7 8 9

Java Arrays

Single Dimensional Arrays

  • An array is a sequence of variables of the same data type (homogenous).
  • The data type can be any of Java’s primitive types or a class (user-defined as well).
  • Each variable in the array is an element.
  • We use an index to specify the position of each element in the array.
  • Arrays are useful for many applications, including calculating statistics or representing the state of a game.
  • Arrays are always homogeneous, or of the same data type.
  • Array indexes always begin with zero (0).
  • Declaring and instantiating arrays
  • In Java Arrays are objects, so they need to be declared and instantiated
  • Types get default values inside the array, just as they do during normal instantiation. Examples:
    int[] array;
    int[] array = new int[9];
    int[] array = {1,2,3,4,5};
    Auto[] array = {new Auto()}; 

     

Declaring arrays:

double [] dailyTemps; // elements are doubles
String [] cdTracks; // elements are Strings
boolean [] answers; // elements are booleans
Auto [] cars; // elements are Auto references
int [] cs101, bio201; // two integer arrays

Instantiating these arrays:

dailyTemps = new double[365]; // 365 elements
cdTracks = new String[15]; // 15 elements
int numberOfQuestions = 30;
answers = new boolean[numberOfQuestions];
cars = new Auto[3]; // 3 elements
cs101 = new int[5]; // 5 elements
bio201 = new int[4]; // 4 elements

Initialization List
The initialization list can only be used when instantiating the array, trying to do so after initialization will cause a compilation error. Example: int[] array = {1,2,3,4,5};
Aggregate Array Operations
- You can perform the same operations on arrays as we do on a series of input values.
- To perform an operation on all elements in an array, we use a for loop to perform the operation on each element.

in turn. For Example tp print all elements of an array:
for(int i=0; i<array.length;i+) {
System.out.println(cellBills[i]);
}

Reading Items Into Array

import java.util.Scanner;
public class GetArrayValues
{
public static void main( String [] args )
{
Scanner scan = new Scanner( System.in );
double [] scores = new double[6];
for ( int i = 0; i < scores.length; i++ )
{
System.out.println( "Enter Score: "
+ ( i + 1 ));
scores[i] = scan.nextDouble( ); // read current bill
}
}
}

Summing the Elements of an Array

import java.text.NumberFormat;
public class SummingArrayElements
{
public static void main( String [] args )
{
double total = 0.0;
double [] scores = new double [6];
scores[0] = 12.2; scores[1] = 33.90;
scores[2] = 16.00; scores[3] = 22.00;
scores[4] = 11.00; scores[5] = 134.90;

for ( int i = 0; i < scores.length; i++ )
{
total += scores[i];
}
System.out.println( "Scores Total: " total);
}
}

Copying Arrays
Arrays are reference types, so by declaring a reference and assigning it to an existing array, you are not creating two objects, you are just creating two references that point to the same array. Manipulation of one of these objects will affect the other. 

Changing an Array’s Size in Array
An array’s length is a fixed length; to grow an array size you need to create a new array of the required size, and copy the existing elements in the old array to the new array, and fill in the rest with your new values.  Two ways to make a copy of an array:
1. Use loops (for, while, etc) to copy individual elements

// Create the original array
int[] originalArray = { 1,5, 14, 33 };
// Define 2nd array
int[] arrayCopy = new int[originalArray.length];
// Copy individual elements
for (int element = 0; element < originalArray.length; element++)
{
arrayCopy[element] = originalArray[element];
}

2. Use System.arraycopy() method

int[] originalArray = { 7, 4, 5, 2 };
int[]arrayCopy = new int[originalArray.length];
// Copy using arrayCopy()
System.arraycopy(originalArray, // Source array
0, // Source array position
arrayCopy, // Target array
0, // Target array position
originalArray.length);

Methods with Array Parameters
To define a method with an array as a parameter use the following syntax:
accessModifier returnType methodName(dataType[] arrayName) { … }
To define a method with an array as a return type use the following syntax
accessModifier dataType[] methodName() { … }
To pass an array as an argument, use the array name without the brackets
methodName(myArray);
Accessors for Arrays
To preserve data integrity, the Accessor should return a copy of the array, and not the reference to that array.
Retrieving Command Line Arguments.  The main method accepts an array of strings. That array holds the arguments, if any, that the user sends to the program from the command line.

public class Arguments {
public static void main( String [] args ) {
for ( int i = 0; i < args.length; i ++ ) {
System.out.println( "args[" + i + "]: " + args[i] );
}
System.out.println( "Total parameters"
+ args.length );
}
}
 

 

Java Tutorial Home 2 3 4 5 6 7 8 9

 

 


Java Tutorial


| Home | Hosting | Domains | Support |  Contacts |
|
Terms & Condition | Privacy Policy |


 

Copyright © 2005 by HostItWise.com Read our Copyright. All rights reserved.

LasX.com | Garage Door Company | BidoBee.com | RushRash Inc