Java arrays and objects

Arrays in Java

Array in java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays.

  • In Java, all arrays are dynamically allocated. (discussed below)
  • Arrays are stored in contiguous memory [consecutive memory locations].
  • Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered, and each has an index beginning with 0.
  • Java array can also be used as a static field, a local variable, or a method parameter.
  • The size of an array must be specified by int or short value and not long.
  • The direct superclass of an array type is Object.
  • Every array type implements the interfaces Cloneable and java.io.Serializable.
  • This storage of arrays helps us randomly access the elements of an array [Support Random Access].
  • The size of the array cannot be altered(once initialized). However, an array reference can be made to point to another array.

An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class depending on the definition of the array. In the case of primitive data types, the actual values are stored in contiguous memory locations. In the case of class objects, the actual objects are stored in a heap segment.

Читайте также:  Css item by type

Creating, initializing, and accessing an Array

One-Dimensional Arrays:

The general form of a one-dimensional array declaration is

type var-name[]; OR type[] var-name;

An array declaration has two components: the type and the name. type declares the element type of the array. The element type determines the data type of each element that comprises the array. Like an array of integers, we can also create an array of other primitive data types like char, float, double, etc., or user-defined data types (objects of a class). Thus, the element type for the array determines what type of data the array will hold.

// both are valid declarations int intArray[]; or int[] intArray; byte byteArray[]; short shortsArray[]; boolean booleanArray[]; long longArray[]; float floatArray[]; double doubleArray[]; char charArray[]; // an array of references to objects of // the class MyClass (a class created by // user) MyClass myClassArray[]; Object[] ao, // array of Object Collection[] ca; // array of Collection // of unknown type

Although the first declaration establishes that int Array is an array variable, no actual array exists. It merely tells the compiler that this variable (int Array) will hold an array of the integer type. To link int Array with an actual, physical array of integers, you must allocate one using new and assign it to int Array.

Instantiating an Array in Java

When an array is declared, only a reference of an array is created. To create or give memory to the array, you create an array like this: The general form of new as it applies to one-dimensional arrays appears as follows:

Читайте также:  Application exception system exception java

Here, type specifies the type of data being allocated, size determines the number of elements in the array, and var-name is the name of the array variable that is linked to the array. To use new to allocate an array, you must specify the type and number of elements to allocate.

int intArray[]; //declaring array intArray = new int[20]; // allocating memory to array
int[] intArray = new int[20]; // combining both statements in one

Note:

The elements in the array allocated by new will automatically be initialized to zero (for numeric types), false (for boolean), or null (for reference types). Do refer to default array values in Java.

Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

Array Literal

In a situation where the size of the array and variables of the array are already known, array literals can be used.

int[] intArray = new int[]< 1,2,3,4,5,6,7,8,9,10 >; // Declaring array literal
  • The length of this array determines the length of the created array.
  • There is no need to write the new int[] part in the latest versions of Java.

Accessing Java Array Elements using for Loop

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.

// accessing the elements of the specified array for (int i = 0; i < arr.length; i++) System.out.println("Element at index " + i + " : "+ arr[i]);

Implementation:

Источник

Arrays of Objects in Java | Example Program

Scientech Easy

Arrays of Objects in Java | So far, we have studied in the previous tutorial that an array in java is an ordered, sequential group of elements. These elements can be either primitive types or reference types.

The main difference between arrays of primitive types and arrays of reference types is that primitive type values can be directly assigned to elements of primitive type arrays.

But, it does not happen in reference-type elements. In the case of an array of reference types, each element contains a reference (normally address ) to an object in the memory.

When we create an array of references in memory, actually, we are not automatically creating an object of each element.

Each reference element is automatically initialized to null and the object that we want it to point to must be explicitly built. (Or the object must already exist somewhere in the memory and be accessible).

To demonstrate these concepts we will understand arrays of objects in java in detail.

Arrays of Objects in Java

An array of objects in Java is just a list of reference variables that contain normally addresses to the individual objects.

When arrays of objects are allocated in the heap memory, only the references for objects are created, no objects are actually created. The actual objects to be stored must be allocated individually at runtime.

In other simple words, for arrays of objects, an object must be created separately for each element in the array.

Let’s understand the concepts of an array of objects in java with help of examples more clearly.

Suppose we have a class Student and we have created an array of students.

Student[ ] st = new Student[5]; // An array of objects of length 5 is declared and created.

Let’s understand this statement in three steps with a diagram.

Step 1 : Declare a Student array variable.

Here, we have declared Student array variable, that can hold a reference to an array object of Students. At present, this array is empty does not hold references to any instances of Student.

Step 2 : After declaring Student array variable, the next step is to create Student array object with a length of 5 by using the new operator, and assign it to that Student variable st.

It creates an array capable of holding 5 Student objects. When we create an array of objects using new operator in java, all its slots automatically are initialized with null.

Note : Java keyword null refers to null object and can be used for any object reference.

Student! We have an array of Student references, but no actual Student objects.

Step 3 : Now, create new Student objects, and assign them to the array elements like this:

st[0] = new Student(); st[1] = new Student(); st[2] = new Student(); st[3] = new Student(); st[4] = new Student();

Here, five new Student objects are created and their memory location is assigned to the Student reference located in st[0], st[1], st[2], st[3], and st[4], respectively. Look at the below figure to understand better.

Arrays of objects in Java

The above figure shows that the creation of an array of objects in java consists of three-stage processes that are as follows:

1. Create an array variable that can reference an array of appropriate types of objects.

2. Create an array of objects.

3. Fill the array of objects with instances of the appropriate type.

Example Program based on Array of Objects

1. Let’s take a very simple example program where we will create an array of Student objects of length 5 and assign new Student objects to the array elements. Look at the source code below to understand more clearly.

Program code:

package arraysProgram; public class Student < String name; int rollNo; Student(String name, int rollNo) < this.name = name; this.rollNo = rollNo; >> package arraysProgram; public class ArraysOfObjects < public static void main(String[] args) < // Creating an array of Student objects of length 5. Student[ ] st = new Student[6]; // Assigning new Student objects to the array elements. st[0] = new Student("John", 1); st[1] = new Student("Ivaan", 2); st[2] = new Student("Deepak", 3); st[3] = new Student("Amit", 4); st[4] = new Student("Rashmi", 5); st[5] = new Student("Herry", 6); // Accessing elements of the specified array of objects using array references. for(int i = 0; i < st.length; i++) < System.out.println("Name: " +st[i].name+ ", "+"Roll no: " +st[i].rollNo); >> >
Output: Name: John, Roll no: 1 Name: Ivaan, Roll no: 2 Name: Deepak, Roll no: 3 Name: Amit, Roll no: 4 Name: Rashmi, Roll no: 5 Name: Herry, Roll no: 6

Creating an array of Student objects and assigning new Student objects to the array elements can also be done like this:

Look at the below figure to understand the memory allocation of an array of Student objects.

Memory allocation of an array of objects in java

In this program, we have declared and created an array of Student objects of length 6. As shown in the above figure, object reference variable st contains an address that is stored in the stack memory.

This reference st will point to an array of Student object references in the heap memory that is initialized with null initially.

When we have created instances of Student object, its memory location is created in heap and is assigned to the array of object references stored in heap memory. For example, st[0] now points to a dynamically allocated Student object.

2. Let’s create another program based on the arrays of objects in java. In this program, we will create an array of School objects and fill array objects with instances of School object.

After initialization, we will send different values to variables declared in School class by using array references for separate School objects and then display them on the console.

Program code:

package arraysProgram; public class School < String stName; String scName; int rollNo; double per; void display() < System.out.println(stName+ " " +scName+ " " +rollNo+ " " +per+ "%"); >> package arraysProgram; public class SchoolTestDrive < public static void main(String[ ] args) < // Create a School array. School[ ] sc = new School[3]; // Put some School into it. sc[0] = new School(); sc[1] = new School(); sc[2] = new School(); // Accessing School using array references. sc[0].stName = "Ivaan"; sc[1].stName = "Deepak"; sc[2].stName = "Herry"; sc[0].scName = "RSVM"; sc[1].scName = "DPS"; sc[2].scName = "DAV"; sc[0].rollNo = 2; sc[1].rollNo = 5; sc[2].rollNo = 8; sc[0].per = 98.8; sc[1].per = 99; sc[2].per = 97.5; int x = 0; while(x < sc.length) < sc[x].display(); x = x + 1; >> >
Output: Ivaan RSVM 2 98.8% Deepak DPS 5 99.0% Herry DAV 8 97.5%

3. Let’s create a program based on an array of objects in which we will store objects of three classes A, B, and C into it and access methods of classes A, B, and C using their array references.

Program code:

public class A < int x; A(int x) < this.x = x; >void m1() < System.out.println("Value of x: " +x); >> public class B < int y; B(int y) < this.y = y; >void m2() < System.out.println("Value of y: " +y); >> public class C < int z; C(int z) < this.z = z; >void m3() < System.out.println("Value of z: "+z); >> public class ArrayObjects < public static void main(String[] args) < A[ ] a = new A[1]; B[ ] b = new B[1]; C[ ] c = new C[1]; a[0] = new A(25); b[0] = new B(30); c[0] = new C(35); a[0].m1(); b[0].m2(); c[0].m3(); >>
Output: Value of x: 25 Value of y: 30 Value of z: 35

In the above program 3, we have declared and created arrays of objects of three different classes A, B, and C of the same length 1 and then assigned arrays of objects with instances of classes A, B, and C. We have easily accessed methods of three classes using array references.

Now, we will modify something in this program. Now, we will declare and create an array of Object objects of length 3 and assign array objects with instances of three classes A, B, and C.

But in this program, we need to do type casting to access methods of these classes. Look at the source code to understand better.

Program code:

Output: Value of x: 20 Value of y: 40 Value of z: 50

Program code: For practice and enhance your knowledge.

public class X < String m1() < System.out.println("m1-X"); return null; >> public class Y < Object m2()< System.out.println("m2-Y"); return null; >> public class ArrayObjects < public static void main(String[] args) < // Creating an array of Objects of length 2. Object[ ] obj = new Object[3]; obj[0] = new X(); obj[1] = new Y(); obj[2] = new Object(); ((X) obj[0]).m1(); ((Y) obj[1]).m2(); System.out.println(obj[2]); >>

Key points associated with arrays of Objects in Java:

1. Arrays are always objects in java whether we declare to hold primitives or object references.

2. A reference variable can be used to access a method or instance variable using dot operator (.).

3. An object reference variable has a value of null when it is not referencing any object.

4. An array of object references can take objects of any type.

5. Java compiler cannot determine which objects are stored in an array.

6. Several objects of different data types (such as an Object, Person, or Car) added in an array cane only be determined at runtime by JVM.

Hope that this tutorial has explained almost all the important points associated with arrays of objects in java with different example programs. I hope that you will have understood the basic concepts of java arrays of objects.

If you get anything incorrect in this tutorial, then please inform our team via email. Your email will be precious to us.
Thanks for reading.
Next ⇒ Annotations in Java ⇐ Prev Next ⇒

Источник

Оцените статью