You are on page 1of 3

SHINE for Core Java - Sec5

Page 1 of 3

SHINE for Core Java


SH INE fo r Cor e J av a > Ja v a 1 1 _ Ma y2 01 0 > Se c5

All Sites

Advanced Search

Sec5
UCF CoreJava 1.1
In this section, we will discuss the following topic l Arrays

Arrays
In Java, Arrays are objects that store a set of elements in an order. It is simply a sequence of memory locations for storing data set out in such a way that any one of the individual locations can be accessed by quoting its index number. Within Java, arrays know their size, and they are always indexed from position zero. Therefore, we can ask the array how big it is by looking at the sole instance variable for an array.length. The individual items within an array are called elements. We can call Array is a sequence of objects or primitives of same type under one umbrella called identifier name. The array is a simple linear sequence, which makes element access fast. Arrays are subclass of Object and implement both the Serializable and Cloneable interfaces. It is possible to create an array with definite size and type of element and assigned the value or fills the array. It is not possible to change the size of an array once you have declared its size. It is possible to copy the contents to another larger array.The array is the most efficient way that Java provides to store and access a sequence of Objects ( Object Handles).There are various methods associated with the java.util.Arrays class for manipulating arrays, these include sorting, searching and filling methods. Let us get an overview of the declaring, initializing and copying arrays. Declarations & Initialization : float[] variable; float variable[]; For array declaration, the brackets can be in one of three places: float[] variable and float variable[]. The first says that the variable is of type float[]. While the other one says that the variable is an array and that the array is of type float. The new operator is used to create or initialize an array. When you create an array, you must specify its length. Once an array has been declared, memory can be allocated to it. Following is the way of Initializing the array. Variable = new float[10]; Address = new String[50]; Declaration & Initialization can be done at once. float Variable[] = new float[10]; String Address = new String[50]; double gears[] = new double[5]; gears[0] = 4.624; gears[1] = 3.231; gears[2] = 2.893; gears[3] = 1.052; gears[4] = 0.962; Sometimes it is convenient to initialize an array immediately during its declaration. double wheels[] = {4.624, 3.231, 2.893, 1.052, 0.962}; [ Although the new operator is not present, the array is allocated dynamically (compiler does it for us) ]. When we declare a variable such as int[] a = new int[10]; It is a reference to an array. So after assignment int[] b = a; both a and b point to the same array and when we change a value of a[0], the value of b[0] is also changed. Copying Array The java.lang.System.arraycopy() method provides efficient copy of data from one array into another. char from[] = {'a', 'b', 'c', 'd', 'e', 'f'}; char to[] = new char[3]; System.arraycopy(from, 2, to, 0, to.length); Note: Destination array must be allocated before arraycopy() is called and must be large enough to contain the data being copied. Default values of Array Unlike other variables that act differently between class level creation and local method level creation, Java arrays are always set to default values. Array Type byte short int long float double char boolean Object Default value 0

0.0 \u0000 false null

Multidimensional Array Multidimensional array is in fact one-dimensional array containing arrays as its elements. I.e. These multidimensional arrays are implemented as arrays of arrays. Ex : int[][] orderItems; Each of the pairs of square brackets represents one dimension, so this is a two-dimensional array. To access a single int element of this two-dimensional array, you must specify two index values, one for each dimension. Assuming that this array was actually initialized as a multiplication table, the int value stored at any given element would be the orderItems of the two indexes. That is, orderItems[3][4] would be 12, and orderItems[5][7] would be 35. The new keyword performs this additional initialization automatically for you. It works with arrays with more than two dimensions as well: int[][][] localResource = new int[200][100][50]; When using new with multidimensional arrays, you do not have to specify a size for all dimensions of the array, only the leftmost dimension or dimensions. For example, the

https://gateway.wipro.com/sites/1073/GDO/UCF/SHINE/CoreJava/Java11_May2010... 24-10-2010

SHINE for Core Java - Sec5

Page 2 of 3

following two lines are legal: int[][][] localResource = new int[100][][]; int[][][] localResource = new int[100][200][]; The first line creates a single-dimensional array, where each element of the array can hold a int[][]. The second line creates a two-dimensional array, where each element of the array is a int[]. If you specify a size for only some of the dimensions of an array, however, those dimensions must be the leftmost ones. The following lines are not legal: int[][][] localResource = new int[100][][200]; // Error! int[][][] localResource = new int[][100][200]; // Error! Take away points 1) Arrays are first class object

2) Arrays subclass Object, developer can synchronize on an array variable and call its wait() and notify() methods 3) Array indices cannot be of type long. Because only non-negative integers can be used as indices, this effectively limits the number of elements in an array to 2,147,483,648,
or 231 , with a range of indices from 0 to 231 -1.

4) When an array is passed as an argument to a method, a reference to the array is passed. This permits you to modify the contents of the array and have the calling routine
see the changes to the array when the method returns. In addition, because a reference is passed around, you can also return arrays created within methods and not worry about the garbage collector releasing the array's memory when the method is done.

5) When you create an array of primitive elements, the array holds the actual values for those elements. Example int IntValue = new int[1,2,3,4,5,6,7,8,9,10]; Stack would be
holding the variable ( IntValue) of type int whereas heap would be storing the value of the ( IntValue) which is 1,2,3,4,5,6,7,8,9,10.

6) When you create an array of objects, they are not stored in the actual array. The array only stores references to the actual objects, and initially each reference is null unless
explicitly initialized. For a detailed explanation, please refer the following resources. 1. Refer to Arrays (http://java.sun.com/docs/books/jls/third_edition/html/arrays.html) for detailed information on arrays. 2. Refer to Array (Java 2 Platform SE 5.0) http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Array.html for information on Array API. Sample questions: 1) To declare an array of 52 int point numbers representing cards , which declarations would be valid? A. int card[] = new card[52]; B. int card [52] = new card[52]; C. int card [52] = new card; D. int[] card = new card[52]; Answer D; { This is a correct way of initializing the array in Java}

2) How many objects are present after the following code has executed?
int[] card = new card [52]; int[] vcard ; vcard = card; 52 2 3. 104 4. 1
1. 2.

Answer D;
3) For which of the following requirement, is an array NOT suitable: A. Holding the scores on twelve midterms exams of a class. B. Holding the name, social security number, age, and income of one individual. C. Holding the temperature readings taken every hour throughout a day. D. Holding the total sales a store made in each of twelve months.

Answer B; { It is suitable for define the variable for such requirements. Array should/can be used where we need to store the multiple values of similar type} Exercises: 1) There are three container each container contains the following value a. REDContainer 1 : 10 , 20 , 30 b. BLUEContainer 2 : 11, 21, 31 c. GREENContainer 3 : 12, 22, 32 Write a program to do the following RED Container 12,22,32 BLUE Container 10,20,30 GREEN Container 11,21,31 While shifting the value from one container to another, we need to ensure that, number should be in a descending order while shifting in the container.

2) Write a program that will read a sequence of positive real numbers entered by the user and will print the same numbers in sorted order from smallest to largest. User can
enter any numbers but print only the positive real numbers. User can terminate the inputs by entering any special character.

3) Write a program which reads in a date and print out what day of the week that date falls on. Program should take three inputs, Day, Month, and Years. Do not use any
if-else statements; instead use a string array consisting of the names of the 7 days of the week.

4) Write a program that will find the average of all the non-zero numbers in the array. (The average is the sum of the numbers, divided by the number of numbers. Array
must be having at least 25 numbers. Declare an array of size 25 and fill with the numbers.

5) Write a program to demonstrate the intersection, union and difference of two arrays. 6) Suppose that a class, Employee, is defined as follows:
class Employee { String lastName; String firstName; int yearsWithCompany; } Suppose that data about 30 employees is already stored in an array: Employee[] employeeData = new Employee[100]; Write a code segment that will output the first name, last name of each employee who has been with the company for 20 years or more.

https://gateway.wipro.com/sites/1073/GDO/UCF/SHINE/CoreJava/Java11_May2010... 24-10-2010

SHINE for Core Java - Sec5

Page 3 of 3

Last modified at 5/21/2010 16:04 by Srinivasan M (WT01 - Global Delivery Organization)

https://gateway.wipro.com/sites/1073/GDO/UCF/SHINE/CoreJava/Java11_May2010... 24-10-2010

You might also like