- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Class with a constructor to initialize instance variables in Java
A class contains a constructor to initialize instance variables in Java. This constructor is called when the class object is created.
A program that demonstrates this is given as follows −
Example
class Student { private int rno; private String name; public Student(int r, String n) { rno = r; name = n; } public void display() { System.out.println("Roll Number: " + rno); System.out.println("Name: " + name); } } public class Demo { public static void main(String[] args) { Student s = new Student(173, "Susan"); s.display(); } }
The output of the above program is as follows −
Roll Number: 173 Name: Susan
Now let us understand the above program.
The Student class is created with data members rno, name. The constructor Student() initializes rno and name. The member function display() displays the values of rno and name. A code snippet which demonstrates this is as follows:
class Student { private int rno; private String name; public Student(int r, String n) { rno = r; name = n; } public void display() { System.out.println("Roll Number: " + rno); System.out.println("Name: " + name); } }
In the main() method, an object s of class Student is created with values 101 and “John”. Then the display() method is called. A code snippet which demonstrates this is as follows:
public class Demo { public static void main(String[] args) { Student s = new Student(173, "Susan"); s.display(); } }
- Related Articles
- How many ways are there to initialize the instance variables of a class in java?
- Can we initialize static variables in a default constructor in Java?
- What are class variables, instance variables and local variables in Java?
- What is the difference between class variables and instance variables in Java?
- Instance variables in Java
- How to initialize a const field in constructor?
- Difference between Static Constructor and Instance Constructor in C#
- How to initialize variables in C#?
- Do static variables get initialized in a default constructor in java?
- How to Use Instance Variables in Ruby
- Can we access the instance variables from a static method in Java?
- How many ways can get the instance of a Class class in Java?
- Sequence of execution of, instance method, static block and constructor in java?
- Accessing variables in a constructor function using a prototype method with JavaScript?
- Class and Static Variables in Java

Advertisements