PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Constructors in Java

← All stacks

Theory

30/270

Constructors in Java

A constructor runs when you create an object. It sets starting values. Same name as the class. No return type — not even void. new Box(4) calls the constructor and creates the object.

If you write no constructor, Java adds an empty default one. A parameterized constructor takes values at creation. You can overload: many constructors with different parameter lists.

void Box() is a normal method, not a constructor. That is the classic trap. Contrast: constructor initialises; method does later work.

Let's take this on the board with one tiny Main class — no extra files. Constructors in Java — output: 4. new Box(4) runs the constructor and sets side. No setter needed. Start from main, go line by line, and stop at each print. That output is the proof for Constructors.

Exam tip

Contrast constructor vs method: return type is the difference.

Example

class Box {
  int side;
  Box(int s) { side = s; }
}

public class Main {
  public static void main(String[] args) {
    Box b = new Box(4);
    System.out.println(b.side);
  }
}

Constructors in Java — output: 4. new Box(4) runs the constructor and sets side. No setter needed.

Short notes

  • DefConstructor runs when new creates the object. Sets starting values.
  • RuleSame name as class. No return type. Called by new.
  • RememberJava adds a default constructor only if you write none.
  • Trapvoid Box() is a method, not a constructor.

Questions

1

When does a constructor run?

2

Can a constructor have a return type?

3

What is constructor overloading?

4

What is void Box()?

Previous← Methods in JavaNextstatic keyword in Java →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.