Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
Now Reading
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
Constructors in Java are blocks of code that can be seen whenever an instance of a class is created. In function, constructors are similar to methods, but there are two key differences. Unlike methods, constructors in Java do not have a return type, and it carries the same name as the class.
In programming, a constructor can be used to create an instance of a class. The function of a constructor is to return the object to a class; thus, it does not have a return type. Constructors are a type of special method that is used to initialize the object in a class.
There are two main types of constructors in Java: parameterized and default constructors. A default constructor in Java is the constructor implemented by Java if a constructor is not explicitly defined.
This tutorial will discuss the default constructor in Java with examples.
In Java, programmers are not always required to implement a constructor in class codes. But if we don’t, the compiler will automatically create and implement a constructor. This is the default constructor in Java, and it has no parameters.
There are a few ways to identify a default constructor. Firstly, default constructors have no arguments in them. Their only function is initializing objects and returning them to the calling codes. The online Java compiler only creates a default constructor if the programmer does not provide any constructors in the entire program.
Another important detail to remember is that no-arg or no-argument constructors are also very similar to default constructors because none have arguments in them. However, a no-arg constructor is built by a programmer, while the default constructor in Java is not.
public class Car {
private String brand;
private String color;
// Default constructor
public Car() {
brand = "Unknown";
color = "Unspecified";
}
public String getBrand() {
return brand;
}
public String getColor() {
return color;
}
public static void main(String[] args) {
// Create an instance of Car using the default constructor
Car car = new Car();
// Access and print the brand and color
System.out.println("Brand: " + car.getBrand());
System.out.println("Color: " + car.getColor());
}
}
In this example, the Car class has a default constructor defined with no parameters. Inside the constructor, the brand variable is set to "Unknown" and the color variable to "Unspecified". When a new Car object is created using the new Car() statement in the main method, the default constructor is invoked, and the brand and color variables are initialized with the default values.
The main method then accesses the brand and color variables using the appropriate getter methods and prints their values.
So what exactly is the purpose of a default constructor? It is important to provide a constructor while defining a class. However, if a programmer chooses not to do that, then Java provides a no-argument constructor on their behalf. As we mentioned before, the constructor's name always matches the class, making it easier to understand and identify.
If a programmer forgets to add a constructor in object-oriented programming, Java provides a default constructor. It only assigns the default values while initializing the objects. It provides:
Any integer variable is assigned with the value of 0 by a default constructor. That is why, if you run a code with the aforementioned values, your output will always be 0.
When creating constructors in Java, there are certain rules and guidelines that we need to follow. Here are the rules for creating Java constructors:
There are three types of constructors in Java:
Syntax:
Syntax:
Syntax:
public class Person {
private String name;
private int age;
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
// Create Person objects using the parameterized constructor
Person person1 = new Person("Aritra Bandyopadhyay", 26);
System.out.println(person1.getName()); // Output: Aritra Bandyopadhyay
System.out.println(person1.getAge()); // Output: 26
Person person2 = new Person("Manisha Pal", 27);
System.out.println(person2.getName()); // Output: Manisha Pal
System.out.println(person2.getAge()); // Output: 27
}
}
In the above example, the Person class has a parameterized constructor that takes two parameters: name of type String and age of type int. Inside the constructor, the values of these parameters are assigned to the corresponding instance variables this.name and this.age. With this parameterized constructor, you can create Person objects by providing values for name and age during object creation.
Constructor overloading in Java allows a class to have multiple constructors with different parameter lists. Each constructor can initialize the object differently, providing flexibility and convenience when creating objects.
public class Rectangle {
private int length;
private int width;
// Default constructor
public Rectangle() {
length = 0;
width = 0;
}
// Constructor with length and width parameters
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
// Constructor with only length parameter (assuming square)
public Rectangle(int length) {
this.length = length;
this.width = length;
}
// Getters and setters
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public static void main(String[] args) {
// Create objects using different constructors
Rectangle rectangle1 = new Rectangle(); // Default constructor
Rectangle rectangle2 = new Rectangle(5, 10); // Constructor with length and width
Rectangle rectangle3 = new Rectangle(7); // Constructor with only length (square)
// Print the dimensions of the rectangles
System.out.println("Rectangle 1: Length = " + rectangle1.getLength() + ", Width = " + rectangle1.getWidth());
System.out.println("Rectangle 2: Length = " + rectangle2.getLength() + ", Width = " + rectangle2.getWidth());
System.out.println("Rectangle 3: Length = " + rectangle3.getLength() + ", Width = " + rectangle3.getWidth());
}
}
In the main method, we create three Rectangle objects using different constructors and print their dimensions for this program.
(Car.java file)
Code for Car.java file:
public class Car {
private String brand;
private String model;
private int year;
// Copy constructor
public Car(Car other) {
this.brand = other.brand;
this.model = other.model;
this.year = other.year;
}
// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Getters and setters
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", model=" + model + ", year=" + year + "]";
}
}
Code for Main.java file:
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Camry", 2022);
// Create a new car object using the copy constructor
Car car2 = new Car(car1);
// Modify the brand of car2
car2.setBrand("Honda");
// Print the details of both cars
System.out.println(car1); // Output: Car [brand=Toyota, model=Camry, year=2022]
System.out.println(car2); // Output: Car [brand=Honda, model=Camry, year=2022]
}
}
In the above example, we have a Car class with three instance variables: brand, model, and year. The class has two constructors - a parameterized constructor and a copy constructor.
The copy constructor takes an object of the same class (Car) as a parameter and initializes the new object with the values of the passed object. This ensures that the new object is a separate copy with its own memory space.
We then create car1 using the parameterized constructor and car2 using the copy constructor, passing car1 as the argument. Modifying the brand of car2 does not affect car1, as they are separate objects with their own memory space.
Constructors are very important when it comes to object-oriented programming. Not only does a constructor help initialize an object when it’s being created, but it also sets the values of the data members of an object.
A constructor is usually created by the programmer while writing the code, but if the programmer skips it or forgets it, Java adds a default constructor. The default constructor in Java initializes the object by assigning a default value to an object before initializing it.
1. What is parameterized constructor in Java?
When a programmer creates a constructor in Java with a few specific parameters and arguments, it is known as parameterized constructor. Unlike a default constructor, a parameterized constructor assigns different values to different objects in a class before initializing it.
2 Why are constructors used in Java?
Initializing instance variables of classes is the main job of constructors in Java. It also informs us about the dependencies in a class.
3. What is constructor overloading in Java?
If a programmer uses more than one constructor with different parameters, it is called a constructor overload. It can help all of the different constructors perform different tasks. But always remember to put different signatures to these different overloaded constructors.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...