When you talk of Java the first thing that comes to mind is Object Oriented Programming. Java is a programming language that deals in objects. This article will focus on Array Of Objects in Java and introduce you object arrays in detail.
This article will touch up on following topics,
- Array Of Objects In Java
- Declaring An Array Of Objects In Java
- Declaring An Array Objects With Initial Values
- Example Program For An Array Of Objects
So let us start with the first topic of discussion
Array Of Objects In Java
The array of objects, as defined by its name, stores an array of objects. An object represents a single record in memory, and thus for multiple records, an array of objects must be created. It must be noted, that the arrays can hold only references to the objects, and not the objects themselves. Let us see how can we declare Array of objects in Java. Make sure you have Java installed n our system.
Declaring An Array Of Objects In Java
We use the class name Object, followed by square brackets to declare an Array of Objects.
Object[] JavaObjectArray;
Another declaration can be as follows:
Object JavaObjectArray[];
Let us see what else can we do with array of objects,
Declaring An Array Objects With Initial Values
Declaration of an array of object can be done by adding initial values. Here, we create an array consisting of a string with the value “Women Empowerment”, as well as an integer with the value 5.
public class Main { public static void main(String[] args) { Object[] JavaObjectArray = {"Women Empowerment", new Integer(5)}; System.out.println( JavaObjectArray[0] ); System.out.println( JavaObjectArray[1] ); } }
The code produces the following output:
Women Empowerment
5
Let finish this article by taking a look at an example,
Example Program For An Array Of Objects
class JavaObjectArray{ public static void main(String args[]){ Account obj[] = new Account[1] ; obj[0] = new Account(); obj[0].setData(1,2); System.out.println("For Array Element 0"); obj[0].showData(); } } class Account{ int a; int b; public void setData(int c,int d){ a=c; b=d; } public void showData(){ System.out.println("Value of a ="+a); System.out.println("Value of b ="+b); } }
Output:
For Array Element 0
Value of a: 1
Value of b: 2
The Object is the root class of all Classes. Array appears to be a convenient data structure for holding multiple values of the same.
Thus we have come to an end of this article on ‘Array Of Objects in Java’. If you wish to learn more, check out the Java Course Online by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible or you can also join our Java Training in Padang.