Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Error’d: Pickup Sticklers

      September 27, 2025

      From Prompt To Partner: Designing Your Custom AI Assistant

      September 27, 2025

      Microsoft unveils reimagined Marketplace for cloud solutions, AI apps, and more

      September 27, 2025

      Design Dialects: Breaking the Rules, Not the System

      September 27, 2025

      Building personal apps with open source and AI

      September 12, 2025

      What Can We Actually Do With corner-shape?

      September 12, 2025

      Craft, Clarity, and Care: The Story and Work of Mengchu Yao

      September 12, 2025

      Cailabs secures €57M to accelerate growth and industrial scale-up

      September 12, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Using phpinfo() to Debug Common and Not-so-Common PHP Errors and Warnings

      September 28, 2025
      Recent

      Using phpinfo() to Debug Common and Not-so-Common PHP Errors and Warnings

      September 28, 2025

      Mastering PHP File Uploads: A Guide to php.ini Settings and Code Examples

      September 28, 2025

      The first browser with JavaScript landed 30 years ago

      September 27, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured
      Recent
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Use Constructors in Java: A Beginner’s Guide

    How to Use Constructors in Java: A Beginner’s Guide

    July 8, 2025

    Java is an object-oriented programming language that is centred around the concept of objects. Objects are like real-world entities that are created with the new keyword and occupy memory. But all this happens in the front-end code – so what about the back-end? How are objects created and initialised with values?

    This is where constructors come into play. Constructors are special types of methods with no return type. They are basically used to initialise the object, to set up its internal state, or to assign default values to its attributes.

    In this tutorial, we will go deep into the topic of constructors in Java. You’ll learn how they work and why they are essential in object creation and Java programming. By the end, I hope you’ll understand why they’re one of the core concepts of OOP.

    Let’s start…

    Prerequisites

    You don’t need to know anything too advanced to start learning about constructors in Java. Just a basic understanding of Java syntax, classes, objects, methods, parameters, arguments, and access modifiers is enough to get started.

    What we’ll cover:

    • What are Constructors in Java?

      • Constructor syntax:
    • Types of Constructors

      • Default Constructor

      • No Argument constructor

      • Parameterised Constructor

      • Copy Constructor

    • What Happens Behind the Scenes When a Constructor Is Called in Java?

    • How to Use the return Keyword in Constructors

      • Sample Code:

      • Example:

    • Conclusion

    • Frequently Asked Questions

    What are Constructors in Java?

    As mentioned above, constructors are special types of methods that:

    1. do not have a return type (not even void),

    2. have the same name as the class

    3. are called automatically when an object is created using the new keyword.

    A constructor’s main purpose is to initialise a newly created object, to set up its internal state, or to assign default values to its attributes.

    Constructors can also be understood as a special block of code which is called when an object is created – either automatically or manually by hard-coding it – with the values we want to initialise the object with.

    If we’re okay with the object using default values (like 0 for numbers or null for objects), Java will handle that for us automatically. But if we want to give the object specific values when it’s created, we need to write a constructor that takes those values as parameters and uses them to set up the object.

    Constructor syntax:

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{
    
        <span class="hljs-comment">// Default constructor with access modifier</span>
        [access_modifier] ClassName(parameters...) {
            <span class="hljs-comment">// constructor body</span>
        }
    
    }
    

    Examples

    When the constructor is not defined explicitly

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
    
        String brand;
        <span class="hljs-keyword">int</span> year;
    
        <span class="hljs-comment">// No constructor is defined, so Java provides a default one</span>
    }
    
    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
    
            Car car1 = <span class="hljs-keyword">new</span> Car();  <span class="hljs-comment">// Java calls the default constructor</span>
    
            <span class="hljs-comment">// Default values: brand = null, year = 0</span>
            System.out.println(<span class="hljs-string">"Brand: "</span> + car1.brand);
            System.out.println(<span class="hljs-string">"Year: "</span> + car1.year);
        }
    }
    

    Output:

    output of the code in which there is no constructor

    In the above code, we have a Car class with two variables:

    1. brand of type String

    2. year of type int

    Since a class is just a blueprint, we need to create an object to actually use it. This is done in the Main class. When we create a Car object using new Car(), Java looks for a constructor. Because we didn’t define one, the compiler automatically provides a default constructor (one with no arguments).

    This allows us to create the object and print its variables without any errors. The values printed will be the default ones — null for the String, and 0 for the int.

    We’ll dive deeper into how this works behind the scenes later, step by step, so it becomes easier to understand.

    When we have defined a constructor

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
    
        String brand;
        <span class="hljs-keyword">int</span> year;
    
        <span class="hljs-comment">// Constructor with parameters to initialize custom values</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Car</span><span class="hljs-params">(String brandName, <span class="hljs-keyword">int</span> modelYear)</span> </span>{
            brand = brandName;
            year = modelYear;
        }
    }
    
    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
    
            Car car2 = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Toyota"</span>, <span class="hljs-number">2022</span>);  <span class="hljs-comment">// Custom values</span>
    
            System.out.println(<span class="hljs-string">"Brand: "</span> + car2.brand);
            System.out.println(<span class="hljs-string">"Year: "</span> + car2.year);
        }
    }
    

    Output

    Output of the code which has a constructor.

    This is the same code as before, with one key difference: this time, we’ve explicitly defined a constructor. Because of this, the output we see isn’t the default values (null for String, 0 for int), but the custom values we provided.

    How does that happen? Simple – we pass values as arguments when creating the object:

    Car car2 = new Car("Toyota", 2022);

    These values are received by the constructor as parameters and are then used to initialize the object’s variables. As a result, instead of default values, we get the brand and year we specified.

    Types of Constructors

    There are mainly four types of constructors:

    1. Default Constructors

    2. No-Arguments Constructor

    3. Parameterised Constructor

    4. Copy Constructor

    Types of constructors

    Default Constructor

    A type of no-argument constructor that is added by the compiler during the compilation process so that the values of the object can be initialised. It’s only added by the compiler if you don’t add one explicitly.

    Syntax:

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyClass</span><span class="hljs-params">()</span> </span>{
            <span class="hljs-comment">// Constructor body</span>
        }
    
    }
    

    Example

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
    
        <span class="hljs-comment">// No constructor defined here</span>
        <span class="hljs-comment">// Compiler will automatically add a default constructor</span>
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            Bike myBike = <span class="hljs-keyword">new</span> Bike();  <span class="hljs-comment">// Calls the compiler-provided default constructor</span>
            System.out.println(<span class="hljs-string">"Bike object created!"</span>);
        }
    
    }
    

    The code becomes the following after the compiler adds a default constructor during the compilation process:

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
    
        <span class="hljs-comment">// Compiler-added default constructor</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Bike</span><span class="hljs-params">()</span> </span>{
            <span class="hljs-keyword">super</span>();  <span class="hljs-comment">// Calls Object class constructor</span>
        }
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            Bike myBike = <span class="hljs-keyword">new</span> Bike();  <span class="hljs-comment">// Now calls this explicit default constructor</span>
            System.out.println(<span class="hljs-string">"Bike object created!"</span>);
        }
    
    }
    

    Output

    Bike object created!

    Default Constructor

    No Argument constructor

    No-argument constructor is a type of constructor that you explicitly write in your code and that does not contain any parameters.

    Now, you may be wondering…Isn’t it the same as the default constructor? The answer is both yes and no.

    There isn’t much difference between the default constructor and the no-argument constructor, as both do not take any parameters. But there is one key difference.

    The default constructor, as we have already discussed, is a type of no-argument constructor that is automatically added by the compiler when it doesn’t find one in our code. In contrast, a no-argument constructor is a type of constructor that we write in our code.

    In short, if the compiler is the one that is adding a constructor during the compilation process, it’s called a default constructor. But if we are the ones adding the constructor, it’s called a no-argument constructor.

    The main difference between a default constructor and a user-defined constructor is how they are created and what they do.

    • A default constructor is automatically added by the compiler if we don’t add one ourselves. It doesn’t do much – it just calls the parent class (usually the Object class) and sets all variables to their default values. For example, int becomes 0and objects become null.

    • A user-defined constructor is one that we write ourselves. We can add custom logic inside it, set custom values to variables, and use access modifiers like public, private, or protected. This means we can decide how the object should be set up when it is created.

    Note that even if we don’t write super() in our constructor, Java still adds it automatically unless we call another constructor with this() or call a different super(...) with parameters.

    We will understand this deeply in the next section.

    Aspect Default Constructor No-Argument Constructor
    Definition A constructor is automatically provided by the compiler when no other constructors exist. A constructor explicitly written by the programmer that takes no arguments.
    Defined By Compiler Programmer
    Custom Logic Not possible – does only basic, default initialization Yes – can contain any initialization logic
    When Available Only if the class has no constructors defined at all When explicitly written by the programmer
    Purpose To allow object creation with default initialization To allow object creation with programmer-defined behavior

    Syntax:

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ClassName</span><span class="hljs-params">()</span> </span>{
            <span class="hljs-comment">// Body (optional)</span>
        }
    
    }
    

    Example

    Let’s use the same Bike example we used to explain the default constructor.

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Bike</span><span class="hljs-params">()</span> </span>{
            System.out.println(<span class="hljs-string">"Bike object created!"</span>);
        }
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            Bike myBike = <span class="hljs-keyword">new</span> Bike();
        }
    }
    

    Output:

    Bike object created!

    No Argument Construment

    In the above code, we have defined a constructor in our code while writing it. This means that it is an example of a no-argument constructor.

    We know that both types of constructors are defined without any parameters, but what about the body? We haven’t said anything about it. Let’s see what happens if we write code with a no-argument constructor without a body:

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
    
        Bike() {
            <span class="hljs-comment">// No body</span>
        }
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            Bike myBike = <span class="hljs-keyword">new</span> Bike(); <span class="hljs-comment">// Calls the user-defined no-argument constructor</span>
            System.out.println(<span class="hljs-string">"Bike object created!"</span>);
        }
    }
    

    Output:

    Bike object created!

    The code still gets compiled because the compiler adds the super() keyword during the compilation process, which initialises the object using the object class.

    Parameterised Constructor

    A constructor that accepts parameters is called a parameterised constructor and is only used when we have to initialise an object’s attributes with custom values.

    • Parameter refers to the variable listed in the constructor or method definition.

    • Argument is the actual value passed when calling the constructor or method.

    It gives us the flexibility of initiating our object with custom values given at the time of object creation.

    Syntax

    Below is the syntax for a parameterised constructor that takes one parameter:

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{
    
        <span class="hljs-comment">// Data members (instance variables)</span>
        DataType variable1;
    
        <span class="hljs-comment">// Parameterized constructor</span>
        ClassName(DataType param1) {
            variable1 = param1;
        }
    
        <span class="hljs-comment">// Main method to create objects</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            <span class="hljs-comment">// Creating object using parameterized constructor</span>
            ClassName obj = <span class="hljs-keyword">new</span> ClassName(value1);
        }
    }
    

    Example

    We will again use the Bike example for this.

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
    
        String modelName;  <span class="hljs-comment">// instance variable</span>
    
        <span class="hljs-comment">// Parameterized constructor</span>
        Bike(String model) {
            modelName = model;
        }
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            <span class="hljs-comment">// Pass parameter while creating the Bike object</span>
            Bike myBike = <span class="hljs-keyword">new</span> Bike(<span class="hljs-string">"Mountain Bike"</span>);
            System.out.println(<span class="hljs-string">"Bike object created! Model: "</span> + myBike.modelName);
        }
    }
    

    Output:

    Bike object created! Model: Mountain Bike

    Parameterized Constructor

    In this example, we’re working with a Bike class that has an instance variable of String data type called modelName, and a constructor to set the value of that variable.

    The constructor takes a parameter called model and assigns it to modelName. So, when we create a new Bike object and pass in the string “Mountain Bike”, the constructor stores that value in the modelName variable.

    Because of this, when we print out the model name, we see “Mountain Bike” instead of null, which is the default value of the String data type, as now the value of the modelName has been updated.

    Copy Constructor

    A copy constructor is used to create a new object as a copy of the existing object. Unlike C++, Java doesn’t have a default copy constructor. Instead, we have to create our own by creating a constructor that takes an object of the same class as a parameter and copies its fields.

    Syntax

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{
    
        <span class="hljs-comment">// Fields</span>
        DataType1 field1;
        DataType2 field2;
        <span class="hljs-comment">// ... other fields</span>
    
        <span class="hljs-comment">// Normal constructor</span>
        ClassName(DataType1 f1, DataType2 f2) {
            field1 = f1;
            field2 = f2;
            <span class="hljs-comment">// ... initialize other fields</span>
        }
    
        <span class="hljs-comment">// Copy constructor </span>
        ClassName(ClassName other) {
            field1 = other.field1;
            field2 = other.field2;
            <span class="hljs-comment">// ... copy other fields</span>
        }
    }
    

    Example

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
    
        String modelName;  <span class="hljs-comment">// instance variable</span>
    
        <span class="hljs-comment">// Parameterized constructor</span>
        Bike(String model) {
            modelName = model;
        }
    
        <span class="hljs-comment">// Copy constructor</span>
        Bike(Bike otherBike) {
            modelName = otherBike.modelName;
        }
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            <span class="hljs-comment">// Create a Bike object using the parameterized constructor</span>
            Bike myBike = <span class="hljs-keyword">new</span> Bike(<span class="hljs-string">"Mountain Bike"</span>);
            System.out.println(<span class="hljs-string">"Bike object created! Model: "</span> + myBike.modelName);
    
            <span class="hljs-comment">// Create a copy of the existing Bike object using the copy constructor</span>
            Bike copiedBike = <span class="hljs-keyword">new</span> Bike(myBike);
            System.out.println(<span class="hljs-string">"Copied Bike object created! Model: "</span> + copiedBike.modelName);
        }
    }
    

    Output:

    Bike object created! Model: Mountain Bike

    Copied Bike object created! Model: Mountain Bike

    Copy Constructor

    In the above code, we have created a copy constructor to copy the values of the object (myBike) into a new object (copiedBike), which we have defined in the main class.

    But the way the new object is called is a little different. Instead of passing arguments for the constructor, we have passed the original object.

    Why Copy Constructors?

    A copy constructor is used to make a copy of the object, but you can also make a copy using the clone() method or the object.clone() method. So why do we use a copy constructor?

    The copy constructor makes a deep copy, while the clone method makes a shallow copy of the object. There are various things that you should know before using cloning techniques, like CloneNotSupportedException.

    On the other hand, copy constructors are clear and easy to understand, and work well with final fields. We can control how the copy happens (deep vs. shallow) and especially when we are dealing with mutable objects.

    What Happens Behind the Scenes When a Constructor Is Called in Java?

    So, just to recap: when we create an object using the new keyword, a constructor is automatically called. If we haven’t defined any constructors in our class, Java automatically defines a constructor for us.

    But while writing and running our code, we mostly focus on what’s visible in our editor, as in what we can see. Let’s dive a little deeper and explore what happens behind the scenes – at the compiler and JVM level – when an object is created and executed.

    • Step 1: Memory Allocation – When we create an object using a new keyword, Java allocates memory for that object in the heap. This memory is where the object’s fields (also called attributes) will be placed.

    • Step 2: Reference Creation – A reference to this object is stored on the stack, which lets our program interact with the object that lives in the heap.

    • Step 3: Constructor Creation – Java then determines which constructor to call. If no constructor is explicitly defined in our class, the compiler automatically inserts a constructor with no parameters.

    • Step 4: Superclass Constructor Call – Before executing the constructor’s body, Java first calls the constructor of the superclass using the super() keyword. This ensures that the fields inherited from the parent class are properly initialised. If you don’t explicitly write super(), the compiler adds it automatically in the first line of the code, but only if the superclass has a no-argument constructor, unless we’re already calling another constructor via this().

    But don’t use both the super() and this() keywords in the same constructor (you can use them in separate constructors.

    Let’s say that it doesn’t have a super class – then what?

    The answer is simple: Java has an in-built Object class that has a no-argument constructor by default. This is why our classes run smoothly even if we don’t write super() ourselves, as Java calls it in the background.

    That means every class we create is a subclass of the object class:

    Attribute Initialisation:

    At this point, fields get initialised:

    • First, with default values (for example, 0 for int, null for objects),

    • Then, with any explicit initialisations we’ve written (for example, int x = 10), the default values will get replaced by them.

    Constructor Execution:

    And finally, the logic runs. This is where all or some of the attributes defined in the class for object creation are initialised by the parameters used during object creation, with the help of constructors.

    But not every field may get initialised. Fields that are not updated by the constructor will keep the values they already have (either the default value or the explicitly initialised values).

    In short, the constructor gives us the flexibility to customise our object at the time of creation, but it doesn’t automatically set every field unless we explicitly write the logic for it.

    Check the code below to understand better:

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Example</span> </span>{
    
        <span class="hljs-keyword">int</span> a;           <span class="hljs-comment">// default 0</span>
        <span class="hljs-keyword">int</span> b = <span class="hljs-number">10</span>;      <span class="hljs-comment">// explicitly initialized to 10</span>
        String name;     <span class="hljs-comment">// default null</span>
    
        Example(<span class="hljs-keyword">int</span> x) {
            a = x;       <span class="hljs-comment">// only 'a' is set through constructor</span>
            <span class="hljs-comment">// 'b' is not changed, stays 10</span>
            <span class="hljs-comment">// 'name' is not changed, stays null</span>
        }
    
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
            System.out.println(<span class="hljs-string">"a = "</span> + a);
            System.out.println(<span class="hljs-string">"b = "</span> + b);
            System.out.println(<span class="hljs-string">"name = "</span> + name);
        }
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            Example obj = <span class="hljs-keyword">new</span> Example(<span class="hljs-number">5</span>);
            obj.display();
        }
    }
    

    Output:

    Output of the code explaining how constructor work.

    In the above example, we have three data members – a, b, and name. We have already done the declaration and initialisation of the variable b at the beginning and given a value to a at the time of object creation.

    So we can see that:

    1. ‘a’, whose value has been updated by the constructor with the value given at the time of object creation, has the same value

    2. ‘b’, which already had a value and does not get updated by the constructor, prints the same value

    3. the string ‘name’ didn’t have a value, so null was printed instead, as it is the default value of the String data type.

    How to Use the return Keyword in Constructors

    We know that constructors are defined without a return type, but we can use the return keyword in the constructor only to exit the constructor early, not to return a value. Check out the code below.

    Sample Code:

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
    
        String modelName;  <span class="hljs-comment">// instance variable</span>
        <span class="hljs-keyword">int</span> speed;
    
        <span class="hljs-comment">// Parameterized constructor</span>
        Bike(String model, <span class="hljs-keyword">int</span> sp) {
            modelName = model;
            <span class="hljs-keyword">return</span>;
            speed = sp;
        }
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            <span class="hljs-comment">// Pass parameter while creating the Bike object</span>
            Bike myBike = <span class="hljs-keyword">new</span> Bike(<span class="hljs-string">"Mountain Bike"</span>, <span class="hljs-number">20</span>);
            System.out.println(<span class="hljs-string">"Bike object created! Model: "</span> + myBike.modelName);
            System.out.println(<span class="hljs-string">"Speed of the Bike is "</span> + myBike.speed);
        }
    }
    

    Let’s try to understand the above code and the use of the return keyword along with it. We will start with what would happen if the return keyword wasn’t here. The code would have executed without any errors and would have received an output.

    code without the return keyword

    Now, what will happen if we add the return keyword? As we have discussed above, the return keyword will tell the compiler not to go beyond this point in the constructor.

    So whatever we have written in the constructor after the return keyword will not be compiled, and if that had any value and was necessary for the proper execution of our code, the compiler will throw an error.

    code with the return keyword

    The error says it clearly ‘unreachable statement’, which means that the compiler was not allowed to go beyond the return keyword.

    Now that you understand the return keyword, let’s see when you can use it.

    Example:

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bike</span> </span>{
    
        <span class="hljs-comment">// Constructor with a condition to exit early</span>
        Bike(<span class="hljs-keyword">boolean</span> skip) {
            <span class="hljs-keyword">if</span> (skip) {
                System.out.println(<span class="hljs-string">"Constructor exited early"</span>);
                <span class="hljs-keyword">return</span>; <span class="hljs-comment">// Ends constructor execution here</span>
            }
    
            System.out.println(<span class="hljs-string">"Constructor continues..."</span>);
            <span class="hljs-comment">// More initialization logic can go here</span>
            System.out.println(<span class="hljs-string">"Bike object initialized successfully"</span>);
        }
    
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
            System.out.println(<span class="hljs-string">"Creating first bike (skip = true):"</span>);
            Bike bike1 = <span class="hljs-keyword">new</span> Bike(<span class="hljs-keyword">true</span>);  <span class="hljs-comment">// Constructor will exit early</span>
    
            System.out.println(<span class="hljs-string">"nCreating second bike (skip = false):"</span>);
            Bike bike2 = <span class="hljs-keyword">new</span> Bike(<span class="hljs-keyword">false</span>); <span class="hljs-comment">// Constructor will continue</span>
        }
    }
    

    We’ve defined a Bike class that has a constructor with one boolean parameter called skip. Inside the constructor, there’s an if statement that checks if skip is true. If it is, the constructor prints a message and uses the return keyword to exit early. This means the rest of the constructor won’t run.

    But there is no else block. So what happens when skip is false? In that case, the if condition is not true, then the code inside the if statement is not executed (including the return keyword) and the constructor simply continues to the next lines of code. That’s where we do the actual bike initialisation and print a success message.

    In short:

    1. If skip is true, the constructor exits early.

    2. If skip is false, the constructor continues and finishes the setup.

    output of the example explaining return keyword

    This is a simple way to control how much of the constructor runs, based on a condition.

    Conclusion

    In this blog, we have understood many different topics, what a constructor is, its different types, like default constructor, no argument constructor, parameterised constructor and copy constructor, not only with theory but with code examples as well.

    Understanding them will not only enhance our understanding but also help us write modular and well-maintained code in Java. While this concept is also important in OOP, as it is centred around the concept of objects and constructors are the ones that are used to initialise them.

    Frequently Asked Questions

    Q1. Why do we use constructors?

    A: We use constructors because:

    1. They are created automatically by the compiler and initialise the object with default values.

    2. We can initialise all the attributes of the objects in one go.

    3. They prevent incomplete or incorrect object initialisation by ensuring that important data is provided during object creation.

    4. Code maintainability and modularity increase.

    5. We can use objects as soon as they are created.

    Q2. What is the basic difference between Method Overloading and Constructor Overloading?

    A:

    Feature

    Method Overloading

    Constructor Overloading

    Purpose

    To perform different operations with the same method name

    To create objects with different initialisations

    Return Type

    Can have a return type

    Has no return type

    Name

    Can be any valid method name

    Always has the same name as the class

    Usage Context

    Called on existing objects

    Called when creating objects

    You can check out some of my other beginner-friendly articles on my blog:

    1. Understanding abstraction in Java

    2. How to build a Movie App in React using TMDB API?

    3. How to merge two sorted arrays

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleHow to Use Pytest: A Simple Guide to Testing in Pytho
    Next Article The Rise of AI Analytics and What It Means for Industries

    Related Posts

    Development

    Using phpinfo() to Debug Common and Not-so-Common PHP Errors and Warnings

    September 28, 2025
    Development

    Mastering PHP File Uploads: A Guide to php.ini Settings and Code Examples

    September 28, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Microsoft warns of banking malware targeting German speakers

    Development

    Best Payment Gateways in France for 2025

    Development

    IBM Cloud login breaks for second time this week and Big Blue isn’t saying why

    Security

    New Data Management Experience in the Atlas UI

    Databases

    Highlights

    Trump Administration’s Pro-Crypto Stance: A Paradigm Shift in Financial Innovation

    May 30, 2025

    In a groundbreaking move that underscores a pivotal shift in financial policy, the Trump administration has unveiled a bold pro-cryptocurrency stance, setting the stage for the United States to emerge as a global leader in the digital financial revolution. This policy pivot not only reflects the administration’s recognition of cryptocurrency’s transformative potential but also signals a new era of economic innovation and empowerment.The Context: Why Now?Cryptocurrency has transitioned from a niche interest to a mainstream financial instrument, with Bitcoin and other digital currencies capturing the imagination of investors, businesses, and governments worldwide. The Trump administration’s endorsement comes at a time when cryptocurrencies are gaining traction as viable assets for hedging against inflation, facilitating cross-border transactions, and fostering financial inclusion.Vice President JD Vance’s recent address at the Bitcoin 2025 conference in Las Vegas was a watershed moment, as he articulated the administration’s commitment to supporting the crypto ecosystem. His declaration that cryptocurrency represents a “hedge against poor policymaking and inflation” encapsulates the administration’s strategic vision.Key Policy InitiativesTax Incentives for Crypto Adoption:
    The administration plans to introduce tax breaks for businesses and individuals transacting in cryptocurrencies. This initiative aims to encourage wider adoption while bolstering the U.S. economy’s digital transformation.Regulatory Clarity:
    In a move to attract blockchain startups and fintech firms, the administration has committed to creating a regulatory framework that balances innovation with investor protection. This approach is designed to eliminate ambiguities that have historically deterred investment in the crypto sector.Integration of Cryptocurrency in 401(k) Plans:
    The Department of Labor’s revised guidance empowers fiduciaries to include cryptocurrencies in retirement portfolios, offering Americans diversified investment options for their future.Public-Private Partnerships:
    To accelerate blockchain adoption, the administration is fostering collaborations between federal agencies and private-sector innovators. These partnerships aim to explore applications in supply chain management, cybersecurity, and beyond.Strategic ImplicationsThe Trump administration’s pro-crypto stance is not merely a policy decision; it’s a strategic move to position the United States as a trailblazer in the global crypto economy. By embracing digital currencies, the administration aims to:Enhance Financial Sovereignty:
    Reducing reliance on traditional banking systems aligns with the broader goal of fostering a resilient and self-reliant economy.Attract Foreign Investment:
    A crypto-friendly environment is expected to draw significant investment from global tech giants and blockchain startups.Strengthen Geopolitical Standing:
    As nations like China and the European Union intensify their focus on central bank digital currencies (CBDCs), the U.S. seeks to maintain its competitive edge by championing decentralized finance (DeFi).Public Reception and CriticismWhile the policy shift has been lauded by crypto enthusiasts and industry leaders, it has also faced criticism from skeptics who highlight concerns about market volatility, fraud, and environmental impact. The administration’s challenge lies in addressing these issues without stifling innovation.Looking AheadThe Trump administration’s pro-crypto stance marks a significant milestone in the evolution of financial policy. By embracing the potential of cryptocurrencies and blockchain technology, the U.S. is poised to lead a global economic transformation. However, the success of this strategy will depend on the administration’s ability to navigate challenges and build a robust, inclusive framework that benefits all stakeholders.As the world watches, the United States stands at the forefront of a financial revolution. The question remains: Will this bold gamble pay off in securing economic prosperity and technological leadership for generations to come? Only time will tell, but the foundation has been laid for an exciting future.

    How do you find time for cleanup work

    May 1, 2025

    GitLab 18 integrates AI capabilities from Duo

    May 15, 2025

    OpenAI Releases a Practical Guide to Building LLM Agents for Real-World Applications

    April 18, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.