What is a constructor in Java?

A constructor has the same name as the class and no return type. It runs automatically when you use new. If you do not write one, Java gives a default constructor with no parameters.

class Student {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s = new Student("Riya", 88);
        System.out.println(s.name + " " + s.marks);
    }
}
Output

Riya 88

Types: default, parameterized and copy constructors. See Java Constructors.


Learn more about the similar topics:
Tutorials
Java Classes and Objects
Java Constructors
Java static and this Keywords
Java Encapsulation and Access Modifiers
Java Inheritance
Java Polymorphism
Java Abstract Classes
Exercises & Assignments
Build a BankAccount class
Calculate areas with inheritance and polymorphism
Use a sealed interface and pattern matching
Interview Questions & Answers
What is a class and an object in Java?
What is a constructor in Java?
What is the difference between a constructor and a method in Java?
What is the this keyword in Java?
What is the static keyword in Java?
What is the final keyword in Java?
What are the four pillars of OOP in Java?