- 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
Does a constructor have a return type in Java?
No, constructor does not have any return type in Java.
Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.
If the programmer doesn’t write a constructor the compiler writes a constructors on his behalf.
Example
If you closely observe the declaration of the constructor in the following example it just have the name of the constructor which is similar to class and, the parameters. It does not have any return type.
public class DemoTest{ String name; int age; DemoTest(String name, int age){ this.name = name; this.age = age; System.out.println("This is the constructor of the demo class"); } public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter the value of name: "); String name = sc.nextLine(); System.out.println("Enter the value of age: "); int age = sc.nextInt(); DemoTest obj = new DemoTest(name, age); System.out.println("Value of the instance variable name: "+name); System.out.println("Value of the instance variable age: "+age); } }
Output
Enter the value of name: Krishna Enter the value of age: 29 This is the constructor of the demo class Value of the instance variable name: Krishna Value of the instance variable age: 29
Advertisements