Array Of Objects (Example)
**Array of Objects
- Student s []=new Student[2]
- s [ reference (100) , reference 2 (110) ](Array of object where address present)
index(0) index(1)
-heap memory :
-----------------------------------------
| reference 1 (obj) 100 |
| reference 2 (obj) 110 |
| |
-----------------------------------------
(Heap)
*********************************************************************************
import java.util.Scanner;
class Student{
int age;
String name;
Student(int age,String name){
this.age=age;
this.name=name;
}
}
public class Arr_object {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
Student s[]=new Student[2];
for(int i=0;i<s.length;i++) {
s[i]=new Student(0,""); // Initialized object first
System.out.print("Enter Name");
s[i].name=sc.nextLine();
System.out.print("Enter age");
s[i].age=sc.nextInt();
sc.nextLine(); // '\n' takes when we Tap "Enter" thats why
} // use "sc.nextLine()" to take that '\n'
for(int i=0;i<s.length;i++) {
System.out.println(s[i].name+" : "+s[i].age);
}
sc.close();
}
}
Comments
Post a Comment