Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Sitemap

Member-only story

Constructor vs Method in Java (Java Interview QA)

Learn the difference between constructors and methods in Java with simple explanations, syntax, and examples. Understand when and how to use each.

2 min readApr 2, 2025

📌 What is a Constructor?

A constructor is a special block of code used to initialize objects.

✅ Key Characteristics:

  • Has the same name as the class.
  • No return type (not even void).
  • Called automatically when an object is created using new.
  • Can be overloaded (multiple constructors with different parameters).

🧱 Example:

public class Person {
String name;

// Constructor
public Person(String name) {
this.name = name;
}
}
Person p = new Person("Ramesh"); // Constructor is called here

📌 What is a Method?

A method is a block of code that performs an action (like calculating, printing, processing data, etc.).

✅ Key Characteristics:

  • Can have any name.
  • Must declare a return type (void, int, String, etc.).
  • Called manually using the object.
  • Can also be overloaded.

--

--

No responses yet