TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Java Constructor
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java OOPJava Tutorials

Java Constructor

Last updated: Sep 30, 2023 6:28 pm
By Meenakshi Agarwal
Share
8 Min Read
Constructor in Java
SHARE

This tutorial will guide you on what is a constructor in Java. You will know how to write a constructor method for a class and instantiate its object.

Contents
Default constructorConstructor syntaxWhen is a constructor called in Java?Check this example:Types of ConstructorsNo Argument ConstructorsParameterized ConstructorsWhat does a constructor return in Java?Constructor Overloading in JavaRelated Posts

Constructor in Java

A constructor is a specialized routine which acts as a callback function. It means that you don’t need to call it explicitly. Java invokes it automatically while creating the object of a class.

Its purpose is to initialize an object during its creation. Apart from having the same name as its class, constructors are very much like any other member methods.

Please note that constructors don’t have a defined return type. Usually, you will utilize a constructor to give initial values to the local class variables characterized within the class or to play out some other start-up process required to make a new object.

Constructor in Java

Default constructor

All classes have constructors, regardless of whether you create one or not. Java provides a default constructor for every class. The default constructor sets all member variables to zero.

Notwithstanding, when you create a constructor explicitly, the default constructor doesn’t come into the picture.

Constructor syntax

class className {

   // Constructor
   className() {
      // ...
   }

   // Other methods…
   void method1() {
      // ...
   }

   void method2() {
      // ...
   }
}

When is a constructor called in Java?

Whenever your program creates an object using the new() operator, Java runtime checks whether you have an explicit constructor or not.

If it finds one, then it invokes the user-defined constructor else executes the default one that Java provides.

Check this example:

// Create a TestConstructor class
public class TestConstructor {
  int attribute;  // Create a class member

  // Create an eattributeplicit constructor for the TestConstructor class
  public TestConstructor() {
    attribute = 1;  // Set the initial value for the class attribute attribute
  }

  public static void main(String[] args) {
    TestConstructor object = new TestConstructor(); // Create an object of class TestConstructor (It'll trigger the constructor)
    System.out.println(object.attribute); // Display the result
  }
}

Output:

1

Types of Constructors

Constructors for Java are mainly of two types:

  • Default/No-Argument Constructors
  • Parametrized Constructors

No Argument Constructors

This constructor is useful when the programmer does not want to provide any parameters for the object variables or members. With the help of no argument constructors,

  • The local variables of the class get initialized,
  • The objects or instance variables will have predefined and fixed values.
No Argument Constructor Example

Check out the sample code for the no-argument constructor:

public class NoArgConstructor {
  int data;

  public NoArgConstructor( /* No Arguments are passed here */) {
    data = 100;
  }

  public static void main(String[] args) {
    NoArgConstructor oj = new NoArgConstructor();
    System.out.println("data : " + oj.data);
  }
}

Output:

data : 100

Parameterized Constructors

When the programmer needs to define new objects with user-defined values or values that change with time, the programmer needs a constructor that accepts these values as one or more parameters from the user or defines them himself.

  • We can pass parameters or values to a constructor in a similar way as for any other method.
  • Parameters are specified within the parentheses after mentioning the constructor’s name.
Parameterized Constructor Example

Constructors can accept parameters that help to set the attribute values.

Check the below example:

public class Laptop {
  int model_year;
  String model_make;
  String model_name;

  public Laptop(int year, String make, String name) {
    model_year = year;
    model_make = make;
    model_name = name;
  }

  public static void main(String[] args) {
    Laptop myLaptop = new Laptop(2019, "Dell", "Latitude");
    System.out.println(myLaptop.model_year + " " + myLaptop.model_make + " " + myLaptop.model_name);
  }
}

Output:

2019 Dell Latitude

What does a constructor return in Java?

Like other OOP languages, constructors in Java don’t have a return statement to return any user-defined value.

However, they do return the current class instance. Also, it is perfectly alright to add a “return;” statement towards the end of a constructor method.

If you write it before any executable statement, then an unreachable statement error will occur.

public class TestConstructorReturn {
  int data;

  public TestConstructorReturn( ) {
    data = -1;
    return;
  }

  public static void main(String[] args) {
    TestConstructorReturn oj = new TestConstructorReturn();
    System.out.println("data : " + oj.data);
  }
}

Output:

-1

Constructor Overloading in Java

Java allows the overloading of constructors. Its JVM can identify constructors depending on the number of parameters, their types, and the sequence.

See the example below to understand this concept more clearly.

public class ConstructorOverloading {
  int a;
  double b;

  public ConstructorOverloading( ) {
    System.out.println("No argument contructor called.");
    a = 0;
    b = 0.0;
  }

  public ConstructorOverloading( int a, double b) {
    System.out.format("Order (%d, %f) based contructor called.\n", a, b);
    this.a = a;
    this.b = 0.0;
  }

  public ConstructorOverloading( double b, int a) {
    System.out.format("Order (%f, %d) based contructor called.\n", b, a);
    this.a = 0;
    this.b = b;
  }

  public ConstructorOverloading( int value) {
    System.out.format("Type (int: %d) based contructor called.\n", value);
    this.a = value;
    this.b = 0.0;
  }

  public ConstructorOverloading( double value) {
    System.out.format("Type (double: %f) based contructor called.\n", value);
    this.b = value;
    this.a = 0;
  }

  public static void main(String[] args) {
      
    ConstructorOverloading o1 = new ConstructorOverloading();
    System.out.format("a : %d, b : %f \n\n", o1.a, o1.b);

    ConstructorOverloading o2 = new ConstructorOverloading(1, 1.1);
    System.out.format("a : %d, b : %f \n\n", o2.a, o2.b);

    ConstructorOverloading o3 = new ConstructorOverloading(1.1, 1);
    System.out.format("a : %d, b : %f \n\n", o3.a, o3.b);

    ConstructorOverloading o4 = new ConstructorOverloading(1);
    System.out.format("a : %d, b : %f \n\n", o4.a, o4.b);

    ConstructorOverloading o5 = new ConstructorOverloading(1.1);
    System.out.format("a : %d, b : %f \n\n", o5.a, o5.b);
  }
}

Output:

No argument contructor called.
a : 0, b : 0.000000

Order (1, 1.100000) based contructor called.
a : 1, b : 0.000000

Order (1.100000, 1) based contructor called.
a : 0, b : 1.100000

Type (int: 1) based contructor called.
a : 1, b : 0.000000

Type (double: 1.100000) based contructor called.
a : 0, b : 1.100000

Related Posts

Java Class and Object

Inheritance in Java

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Use Java String Format with Examples

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Java Class and Object Concept Java Class and Object Explained
Next Article Java Inheritance Java Inheritance Explained

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x