- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do we initialize an array within object parameters in java?
You can initialize the array variable which is declared inside the class just like any other value, either using constructor or, using the setter method.
Example
In the following Java example, we are declaring an instance variable of array type and initializing it from the constructor.
public class Student { String name; int age; String subs[]; Student(String name, int age, String subs[]){ this.name = name; this.age = age; this.subs = subs; } public void display() { System.out.println("Name: "+this.name); System.out.println("Age :"+this.age); System.out.print("Subjects: "); for(int i = 0; i < subs.length; i++) { System.out.print(subs[i]+" "); } } public static void main(String args[]) { String subs[] = {"Mathematics", "English", "Science", "Social"}; Student obj = new Student("Krishna", 25, subs); obj.display(); } }
Output
Name: Krishna Age :25 Subjects: Mathematics English Science Social
Example2
public class Student { String name; int age; String subs[]; public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setSubs(String[] subs) { this.subs = subs; } public void display() { System.out.println("Name: "+this.name); System.out.println("Age :"+this.age); System.out.print("Subjects: "); for(int i = 0; i < subs.length; i++) { System.out.print(subs[i]+" "); } } public static void main(String args[]) { String subs[] = {"Mathematics", "English", "Science", "Social"}; Student obj = new Student(); obj.setName("Krishna"); obj.setAge(25); obj.setSubs(subs); obj.display(); } }
Output
Name: Krishna Age :25 Subjects: Mathematics English Science Social
- Related Articles
- How do I declare and initialize an array in Java?
- How to initialize an array in Java
- How can we initialize a boolean array in Java?
- How do we check if an object is an array in Javascript?
- How do we pass parameters by value in a Java method?
- 3 ways to initialize an object in Java
- How do we initialize a variable in C++?
- How to initialize an array in JShell in Java 9?
- How to initialize an array using lambda expression in Java?
- Initialize an Array with Reflection Utilities in Java
- How to declare, create, initialize and access an array in Java?
- Initialize tuples with parameters in Python
- How to initialize an array in C#?
- how to initialize a dynamic array in java?
- How to initialize elements in an array in C#?

Advertisements