

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create class Objects in Java using new operator
Class objects can be created in Java by using the new operator. A class is instantiated by the new operator by allocating memory for the object dynamically and then returning a reference for that memory. A variable is used to store the memory reference.
A program that demonstrates this is given as follows:
Example
class Student { int rno; String name; public Student(int r, String n) { rno = r; name = n; } 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(15, "Peter Smith"); s.display(); } }
Output
Roll Number: 15 Name: Peter Smith
Now let us understand the above program.
The Student class is created with data members rno, name. A constructor initializes rno, name and the method display() prints their values. A code snippet which demonstrates this is as follows:
class Student { int rno; String name; public Student(int r, String n) { rno = r; name = n; } 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 by using the new operator. 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(15, "Peter Smith"); s.display(); } }
- Related Questions & Answers
- How to create JavaScript objects using new operator?
- Create Objects of a Class in Java
- The new operator in Java
- How to create class objects in Python?
- Create a queue using LinkedList class in Java
- Placement new operator in C++
- The new operator in JavaScript
- Difference between "new operator" and "operator new" in C++?
- Different ways to create Objects in Java
- Creating JavaScript constructor using the “new” operator?
- Create a new empty file in Java
- Create a Date object using the Calendar class in Java
- new and delete operator in C++
- Get the class name for various objects in Java
- How to create a new directory by using File object in Java?
Advertisements