Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java constructors.

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

Create a constructor:

Try it Yourself »

Note that the constructor name must match the class name , and it cannot have a return type (like void ).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

Advertisement

Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

You can have as many parameters as you want:

Create your site with Spaces

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, get certified.

  • DSA to Development
  • Data Structure & Algorithm Classes (Live)
  • System Design (Live)
  • JAVA Backend Development(Live)
  • DevOps(Live)
  • Data Structures & Algorithms in Python
  • Interview Preparation Course
  • GATE CS & IT 2024
  • Data Science (Live)
  • Data Structure & Algorithm-Self Paced(C++/JAVA)
  • Master Competitive Programming(Live)
  • Full Stack Development with React & Node JS(Live)
  • CBSE Class 12 Computer Science
  • School Guide
  • Python Programming Foundation
  • All Courses
  • DSA for Beginners
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Doubly Circular Linked List
  • Linked List Tutorial
  • Generic Tree
  • Binary Tree
  • Binary Search Tree
  • Red Black Tree
  • Tree Data Structure Tutorial
  • Set Data Structure
  • Map Data Structure
  • Advanced Data Structure
  • Data Structures Tutorial
  • Design and Analysis of Algorithms
  • Asymptotic Analysis
  • Asymptotic Notations
  • Worst, Average and Best Cases
  • Linear Search
  • Binary Search
  • Searching Algorithms Tutorial
  • Selection Sort
  • Bubble Sort
  • Insertion Sort
  • Counting Sort
  • Bucket Sort
  • Sorting Algorithms Tutorial
  • Greedy Algorithms
  • Dynamic Programming
  • Graph Algorithms
  • Pattern Searching
  • Backtracking
  • Divide and Conquer
  • Mathematical Algorithms
  • Geometric Algorithms
  • Bitwise Algorithms
  • Randomized Algorithms
  • Branch and Bound
  • Algorithms Tutorial
  • Complete DSA Tutorial
  • Competitive Programming
  • Facebook SDE Sheet
  • Amazon SDE Sheet
  • Apple SDE Sheet
  • Netflix SDE Sheet
  • Google SDE Sheet
  • Wipro Coding Sheet
  • Infosys Coding Sheet
  • TCS Coding Sheet
  • Cognizant Coding Sheet
  • HCL Coding Sheet
  • DSA Sheet for Beginners
  • FAANG Coding Sheet
  • Love Babbaar Sheet
  • Mass Recruiter Sheet
  • Product-Based Coding Sheet
  • Company-Wise Preparation Sheet
  • Top 100 DSA Interview Questions Topic-wise
  • Top 50 Array Problems
  • Top 50 String Problems
  • Top 50 Stack Problems
  • Top 50 Heap Problems
  • Top 50 Linked List Problems
  • Top 50 Tree Problems
  • Top 50 Graph Problems
  • Top 50 Problems on Recursion Algorithms
  • Top 20 Interview Questions on Greedy Algorithms
  • Top 20 Interview Questions on Dynamic Programming
  • Top 50 Problems on Dynamic Programming (DP)
  • Top 20 Interview Questions on Hashing
  • Interview Questions on Top 10 Algorithms
  • Commonly Asked Data Structure Interview Questions
  • All Puzzles
  • Top 100 Puzzles Asked In Interviews
  • Top 20 Puzzles Commonly Asked During SDE Interviews
  • Top MCQs on Puzzles with Answers
  • Crossword Puzzle Of The Week
  • What is System Design
  • Key Terminologies in System Design
  • Analysis and Architecture of Systems
  • Scalability in System Design
  • Databases in System Design
  • High Level Design or HLD
  • Low Level Design or LLD
  • Communication Protocols
  • Web Servers and Proxies
  • Case Studies in Designing Systems
  • Complete System Design Tutorial
  • Factory Pattern
  • Observer Pattern
  • Singleton Design Pattern
  • Decorator Pattern
  • Strategy Pattern
  • Adapter Pattern
  • Command Pattern
  • Iterator Pattern
  • Prototype Design Pattern
  • All Design Patterns
  • System Design Roadmap
  • Top 10 System Design Interview Questions and Answers
  • Company Preparation
  • Practice Company Questions
  • Interview Experiences
  • Experienced Interviews
  • Internship Interviews
  • Multiple Choice Quizzes
  • Aptitude for Placements
  • Go Language
  • HTML Tutorial
  • Free HTML Course
  • HTML Cheat Sheet
  • CSS Tutorial
  • Free CSS Course
  • CSS Cheat Sheet
  • JavaScript Tutorial
  • Free JavaScript Course
  • JavaScript A to Z Complete Guide
  • JavaScript Cheat Sheet
  • JavaScript Programming Examples
  • ReactJS Tutorial
  • Free ReactJS Course
  • React Material UI
  • React Bootstrap
  • React Suite
  • ReactJS Reactstrap
  • BlueprintJS
  • Node.js Tutorial
  • PHP Tutorial
  • PHP Programming Examples
  • AngularJS Tutorial
  • AngularJS Cheat Sheet
  • Angular PrimeNG
  • Angular ngx Bootstrap
  • jQuery Tutorial
  • jQuery Cheat Sheet
  • jQuery Mobile
  • Bootstrap Tutorial
  • Bootstrap 5
  • Bootstrap Cheat Sheet
  • Tailwind CSS
  • Materialize CSS
  • Semantic UI
  • Spectre CSS
  • Underscore.js
  • TensorFlow.js
  • ML Tutorial
  • ML Projects
  • Data Science using Python
  • Data Science using R
  • Pandas Tutorial
  • NumPy Tutorial
  • Python Data Visualization Tutorial
  • Matplotlib Tutorial
  • Bokeh Tutorial
  • Plotly Tutorial
  • Seaborn Tutorial
  • Data Visualization with R
  • ggplot Tutorial
  • Data Analysis with Python
  • Data Analysis with R
  • Deep Learning Tutorial
  • Deep Learning Projects
  • NLP Tutorial
  • OpenCV Tutorial
  • Machine Learning Interview Question
  • Deep Learning Interview Question
  • Python Interview Questions
  • Top 50 R Interview Questions
  • PyTorch Lightning
  • Mathematics
  • Operating System
  • Computer Networks
  • Computer Organization and Architecture
  • Theory of Computation
  • Compiler Design
  • Digital Logic
  • Software Engineering
  • Microsoft Azure Tutorial
  • Google Cloud Platform
  • English Grammar
  • School Programming
  • Number System
  • Linear Algebra
  • Trigonometry
  • Probability
  • Mensuration
  • Class 8 Syllabus
  • Class 9 Syllabus
  • Class 10 Syllabus
  • Class 11 Syllabus
  • Class 12 Syllabus
  • Class 8 Notes
  • Class 9 Notes
  • Class 10 Notes
  • Class 11 Notes
  • Class 12 Notes
  • Class 8 Formulas
  • Class 9 Formulas
  • Class 10 Formulas
  • Class 11 Formulas
  • Class 8 Maths Solution
  • Class 9 Maths Solution
  • Class 10 Maths Solution
  • Class 11 Maths Solution
  • Class 12 Maths Solution
  • Class 7 SS Syllabus
  • Class 8 SS Syllabus
  • Class 9 SS Syllabus
  • Class 10 SS Syllabus
  • Class 7 Notes
  • History Class 7
  • History Class 8
  • History Class 9
  • Geo. Class 7
  • Geo. Class 8
  • Geo. Class 9
  • Civics Class 7
  • Civics Class 8
  • Political Science
  • Class 11th Notes
  • Class 12th Notes
  • Business Studies Complete Guide
  • Accountancy Complete Guide
  • Microeconomics Complete Guide
  • Statistics for Economics Complete Guide
  • Class 12th notes
  • Macroeconomics Complete Guide
  • Indian Economic Development Complete Guide
  • Economics - Paper 2020 Set 2 (58/2/2)
  • Economics - Paper 2020 Set 2
  • Economics - Paper 2020 Set (58/1/3)
  • Economics - Paper 2020 Set (58/1/2)
  • Accountancy - Paper Code: 67/1/1, 2020
  • Accountancy - Paper Code: 67/1/2, 2020
  • Accountancy - Paper Code: 67/1/3, 2020
  • Accountancy - Paper Code: 67/2/1, 2020
  • Accountancy - Paper Code: 67/2/2, 2020
  • Accountancy - Paper Code: 67/2/3, 2020
  • Accountancy - Paper Code: 67/4/1, 2020
  • Business Studies - Paper-2019 Set 1
  • Business Studies - Paper 2019 Code (66-2-1)
  • Business Studies - Paper-2020 Set 1
  • Business Studies - Paper-2020 Set 2
  • Economics - Paper 2020 Set 1
  • Economics - Paper 2020 Set 2 (58/2/3)
  • Economics - Paper 2020 Set 3
  • Economics - Paper 2020 Set 3 (58/3/2)
  • Economics - Paper 2020 Set 3 (58/3/3)
  • Economics - Paper 2020 Set 4 (58/4/1)
  • Economics - Paper 2020 Set 4 (58/4/2)
  • Economics - Paper 2020 Set 4 (58/4/3)
  • Economics - Paper 2020 Set 5 (58/5/1)
  • Economics - Paper 2020 Set 5 (58/5/2)
  • Economics - Paper 2020 Set 5 (58/5/3)
  • Commerce Complete Guide
  • GATE 2024 Live Course
  • GATE Computer Science Notes
  • Last Minute Notes
  • GATE CS Solved Papers
  • GATE CS Original Papers and Official Keys
  • GATE CS 2023 Syllabus
  • Important Topics for GATE CS
  • GATE 2023 Important Dates
  • ISRO CS Original Papers and Official Keys
  • ISRO CS Solved Papers
  • ISRO CS Syllabus for Scientist/Engineer Exam
  • UGC NET CS Notes Paper II
  • UGC NET CS Notes Paper III
  • UGC NET CS Solved Papers
  • RRB Clerk 2023 Exam
  • SBI Clerk Syllabus
  • General Awareness
  • Quantitative Aptitude
  • Reasoning Ability
  • SBI Clerk Practice Papers
  • SBI PO Syllabus
  • Previous Year Papers
  • SBI PO Practice Papers
  • IBPS PO 2022 Syllabus
  • English Notes
  • Reasoning Notes
  • Mock Question Papers
  • IBPS Clerk Syllabus
  • Geography Notes
  • Modern Indian History Notes
  • Medieval Indian History Notes
  • Ancient Indian History Notes
  • Complete History Notes
  • Science & Tech. Notes
  • Ethics Notes
  • Polity Notes
  • Economics Notes
  • Government Schemes (Updated)
  • UPSC Previous Year Papers
  • SSC CGL Syllabus
  • General Studies
  • Subjectwise Practice Papers
  • Campus Ambassador Program
  • School Ambassador Program
  • Geek of the Month
  • Campus Geek of the Month
  • Placement Course
  • Testimonials
  • Student Chapter
  • Geek on the Top
  • Get Hired: Apply for Jobs
  • Job-a-thon: Hiring Challenge
  • Recruiter Dashboard
  • Corporate Hiring Solutions
  • All DSA Problems
  • Problem of the Day
  • GFG SDE Sheet
  • Beginner's DSA Sheet
  • Love Babbar Sheet
  • Top 50 DP Problems
  • GFG Weekly Coding Contest
  • Job-A-Thon: Hiring Challenge
  • BiWizard School Contest
  • All Contests and Events
  • Saved Videos
  • What's New ?
  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Write an Interview Experience
  • Share Your Campus Experience
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted output in Java
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

Java constructors.

  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • ‘this’ reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • List of all Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Java Singleton Class
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Try, catch, throw and throws in Java
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

Java constructors or constructors in Java is a terminology used to construct something in our programs. A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.

What are Constructors in Java?

In Java, Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

Note: It is not necessary to write a constructor for a class. It is because the java compiler creates a default constructor (constructor with no arguments) if your class doesn’t have any.

How Java Constructors are Different From Java Methods?

  • Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.
  • Constructors do not return any type while method(s) have the return type or void if does not return any value.
  • Constructors are called only once at the time of Object creation while method(s) can be called any number of times.

Now let us come up with the syntax for the constructor being invoked at the time of object or instance creation.

The first line of a constructor is a call to super() or this(), (a call to a constructor of a super-class or an overloaded constructor), if you don’t type in the call to super in your constructor the compiler will provide you with a non-argument call to super at the first line of your code, the super constructor must be called to create an object:

If you think your class is not a subclass it actually is, every class in Java is the subclass of a class object even if you don’t say extends object in your class definition.

Need of Constructors in Java

Think of a Box. If we talk about a box class then it will have some class variables (say length, breadth, and height). But when it comes to creating its object(i.e Box will now exist in the computer’s memory), then can a box be there with no value defined for its dimensions? The answer is N o .  So constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

When Constructor is called?

Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. Rules for writing constructors are as follows:

  • The constructor(s) of a class must have the same name as the class name in which it resides.
  • A constructor in Java can not be abstract, final, static, or Synchronized.
  • Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

So by far, we have learned constructors are used to initialize the object’s state. Like methods , a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.

Types of Constructors in Java

Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in Java are mentioned below:

  • Default Constructor
  • Parameterized Constructor
  • Copy Constructor

1. Default Constructor in Java

A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor can’t change the default constructor.

Note: Default constructor provides the default values to the object like 0, null, etc. depending on the type.

2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.

Remember: Does constructor return any value? There are no “return value” statements in the constructor, but the constructor returns the current class instance. We can write ‘return’ inside a constructor.

Now the most important topic that comes into play is the strong incorporation of OOPS with constructors known as constructor overloading. Just like methods, we can overload constructors for creating objects in different ways. The compiler differentiates constructors on the basis of the number of parameters, types of parameters, and order of the parameters. 

3. Copy Constructor in Java

Unlike other constructors copy constructor is passed with another object which copies the data available from the passed object to the newly created object.

To know deep down about constructors there are two concepts been widely used as listed below: 

  • Constructor Chaining

Frequently Asked Questions(FAQs)

Q1. what is a constructor in java.

A constructor in Java is a special method used to initialize objects.

Q2. Can a Java constructor be private?

Yes, a constructor can be declared private. A private constructor is used in restricting object creation.

This article is contributed by Nitsdheerendra . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org . See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

Please Login to comment...

  • Kirti_Mangal
  • deepak_jain
  • akshaychourey
  • solankimayank
  • anikakapoor
  • nishkarshgandhi
  • kamleshjoshi18
  • hariohmtripathi
  • arunkumar_selvam
  • avinashrat55252
  • Java-Constructors

constructor assignment in java

Improve your Coding Skills with Practice

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types
  • Java Operators
  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else
  • Java switch Statement
  • Java for Loop
  • Java for-each Loop
  • Java while Loop
  • Java break Statement
  • Java continue Statement
  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor
  • Java Strings
  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP (II)

  • Java Inheritance
  • Java Method Overriding
  • Java super Keyword
  • Abstract Class & Method
  • Java Interfaces
  • Java Polymorphism
  • Java Encapsulation

Java OOP (III)

  • Nested & Inner Class
  • Java Static Class
  • Java Anonymous Class
  • Java Singleton
  • Java enum Class

Java enum Constructor

  • Java enum String

Java Reflection

  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java List Interface
  • Java ArrayList
  • Java Vector
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue Interface
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet
  • Java EnumSet
  • Java LinkedhashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator
  • Java ListIterator
  • Java I/O Streams
  • Java InputStream
  • Java OutputStream
  • Java FileInputStream
  • Java FileOutputStream
  • Java ByteArrayInputStream
  • Java ByteArrayOutputStream
  • Java ObjectInputStream
  • Java ObjectOutputStream
  • Java BufferedInputStream
  • Java BufferedOutputStream
  • Java PrintStream

Java Reader/Writer

  • Java Reader
  • Java Writer
  • Java InputStreamReader
  • Java OutputStreamWriter
  • Java FileReader
  • Java FileWriter
  • Java BufferedReader
  • Java BufferedWriter
  • Java StringReader
  • Java StringWriter
  • Java PrintWriter

Additional Topics

  • Java Scanner Class
  • Java Type Casting
  • Java autoboxing and unboxing
  • Java Lambda Expression
  • Java Generics
  • Java File Class
  • Java Wrapper Class
  • Java Command Line Arguments

Java Tutorials

Java this Keyword

  • Java Singleton Class
  • Java Abstract Class and Abstract Methods

Java Constructors

  • What is a Constructor?

A constructor in Java is similar to a method that is invoked when an object of the class is created.

Unlike Java methods , a constructor has the same name as that of the class and does not have any return type. For example,

Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return type.

Recommended Reading: Why do constructors not return values

Example 1: Java Constructor

In the above example, we have created a constructor named Main() . Inside the constructor, we are initializing the value of the name variable.

Notice the statement of creating an object of the Main class.

Here, when the object is created, the Main() constructor is called. And, the value of the name variable is initialized.

Hence, the program prints the value of the name variables as Programiz .

Types of Constructor

In Java, constructors can be divided into 3 types:

  • No-Arg Constructor
  • Parameterized Constructor
  • Default Constructor

1. Java No-Arg Constructors

Similar to methods, a Java constructor may or may not have any parameters (arguments).

If a constructor does not accept any parameters, it is known as a no-argument constructor. For example,

Example 2: Java private no-arg constructor

In the above example, we have created a constructor Main() . Here, the constructor does not accept any parameters. Hence, it is known as a no-arg constructor.

Notice that we have declared the constructor as private.

Once a constructor is declared private , it cannot be accessed from outside the class. So, creating objects from outside the class is prohibited using the private constructor.

Here, we are creating the object inside the same class. Hence, the program is able to access the constructor. To learn more, visit Java Implement Private Constructor .

However, if we want to create objects outside the class, then we need to declare the constructor as public .

Example 3: Java public no-arg constructors

Recommended Reading: Java Access Modifier

2. Java Parameterized Constructor

A Java constructor can also accept one or more parameters. Such constructors are known as parameterized constructors (constructor with parameters).

Example 4: Parameterized constructor

In the above example, we have created a constructor named Main() . Here, the constructor takes a single parameter. Notice the expression,

Here, we are passing the single value to the constructor. Based on the argument passed, the language variable is initialized inside the constructor.

3. Java Default Constructor

If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the execution of the program. This constructor is called default constructor.

Example 5: Default Constructor

Here, we haven't created any constructors. Hence, the Java compiler automatically creates the default constructor.

The default constructor initializes any uninitialized instance variables with default values.

In the above program, the variables a and b are initialized with default value 0 and false respectively.

The above program is equivalent to:

The output of the program is the same as Example 5.

  • Important Notes on Java Constructors
  • Constructors are invoked implicitly when you instantiate objects.
  • The two rules for creating a constructor are: The name of the constructor should be the same as the class. A Java constructor must not have a return type.
  • If a class doesn't have a constructor, the Java compiler automatically creates a default constructor during run-time. The default constructor initializes instance variables with default values. For example, the int variable will be initialized to 0
  • Constructor types: No-Arg Constructor - a constructor that does not accept any arguments Parameterized constructor - a constructor that accepts arguments Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.
  • A constructor cannot be abstract or static or final .
  • A constructor can be overloaded but can not be overridden.
  • Constructors Overloading in Java

Similar to Java method overloading , we can also create two or more constructors with different parameters. This is called constructors overloading.

Example 6: Java Constructor Overloading

In the above example, we have two constructors: Main() and Main(String language) . Here, both the constructor initialize the value of the variable language with different values.

Based on the parameter passed during object creation, different constructors are called and different values are assigned.

It is also possible to call one constructor from another constructor. To learn more, visit Java Call One Constructor from Another .

Note : We have used this keyword to specify the variable of the class. To know more about this keyword, visit Java this keyword .

Table of Contents

  • Example: Java Constructor
  • Java No-Arg Constructors
  • Java Parameterized Constructor
  • Java Default Constructor

Sorry about that.

Related Tutorials

Java Tutorial

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Providing Constructors for Your Classes

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

To create a new Bicycle object called myBike , a constructor is called by the new operator:

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike .

Both constructors could have been declared in Bicycle because they have different argument lists. As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types. You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart. Doing so causes a compile-time error.

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object , which does have a no-argument constructor.

You can use a superclass constructor yourself. The MountainBike class at the beginning of this lesson did just that. This will be discussed later, in the lesson on interfaces and inheritance.

You can use access modifiers in a constructor's declaration to control which other classes can call the constructor.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Default constructor vs. inline field initialization

What's the difference between a default constructor and just initializing an object's fields directly?

What reasons are there to prefer one of the following examples over the other?

  • constructor

Barry Brown's user avatar

  • 11 According to this answer , your Example 1 is actually transformed into your Example 2 under the hood. –  Daniel Jan 7, 2015 at 17:46

5 Answers 5

Initialisers are executed before constructor bodies. (Which has implications if you have both initialisers and constructors, the constructor code executes second and overrides an initialised value)

Initialisers are good when you always need the same initial value (like in your example, an array of given size, or integer of specific value), but it can work in your favour or against you:

If you have many constructors that initialise variables differently (i.e. with different values), then initialisers are useless because the changes will be overridden, and wasteful.

On the other hand, if you have many constructors that initialise with the same value then you can save lines of code (and make your code slightly more maintainable) by keeping initialisation in one place.

Like Michael said, there's a matter of taste involved as well - you might like to keep code in one place. Although if you have many constructors your code isn't in one place in any case, so I would favour initialisers.

davin's user avatar

The reason to prefer Example one is that it's the same functionality for less code (which is always good).

Apart from that, no difference.

However, if you do have explicit constructors, I'd prefer to put all initialization code into those (and chain them) rather than splitting it up between constructors and field initializers.

Michael Borgwardt's user avatar

Should we favor field initializer or constructor to give a default value to a field?

I will not consider exceptions that may rise during field instantiation and field lazy/eager instantiation that touch other concerns than readability and maintainability concerns. For two codes that perform the same logic and produce the same result, the way with the best readability and maintainability should be favored.

choosing the first or the second option is before all a question of code organization , readability and maintainability .

keep a consistency in the way of choosing (it makes overall application code clearer)

don't hesitate to use field initializers to instantiate Collection fields to prevent NullPointerException

don't use field initializers for fields that may be overwritten by constructors

in classes with a single constructor, the field initializer way is generally more readable and less verbose

in classes with multiple constructors where constructors have no or very few coupling between them , the field initializer way is generally more readable and less verbose

in classes with multiple constructors where constructors have coupling between them , none of the two ways is really better but whatever the chosen way, combining it with the chaining constructor is the way (see use case 1).

OP Question

With a very simple code, the assignment during the field declaration seems better and it is.

This is less verbose and more straight :

than the constructor way :

In real classes with so real specificities, things are different. In fact, according to specificities encountered, a way, the other one or anyone of them should be favored.

More elaborated examples to illustrate

Study case 1

I will start from a simple Car class that I will update to illustrate these points. Car declare 4 fields and some constructors that have relation between them.

1.Giving a default value in field intializers for all fields is undesirable

Default values specified in the fields declaration are not all reliable. Only name and origin fields have really default values.

nbSeat and color fields are first valued in their declaration, then these may be overwritten in the constructors with arguments. It is error-prone and besides with this way of valuing fields, the class decreases its reliability level. How could rely on any default value assigned during the fields declaration while it has proven to be not reliable for two fields ?

2.Using constructor to value all fields and relying on constructors chaining is fine

This solution is really fine as it doesn't create duplication, it gathers all the logic at a place : the constructor with the maximum number of parameters. It has a single drawback : the requirement to chain the call to another constructor. But is it a drawback ?

3.Giving a default value in field intializers for fields which constructors don't assign to them a new value is better but has still duplication issues

By not valuing nbSeat and color fields in their declaration, we distinguish clearly fields with default values and fields without.

This solution is rather fine but it repeats the instantiation logic in each Car constructor contrary to the previous solution with constructor chaining.

In this simple example, we could start to understand the duplication issue but it seems only a little annoying. In real cases, the duplication may be much important as the constructor may perform computation and validation. Having a single constructor performing the instantiation logic becomes so very helpful.

So finally the assignment in the fields declaration will not always spare the constructor to delegate to another constructor.

Here is an improved version.

4.Giving a default value in field intializers for fields which constructors don't assign to them a new value and relying on constructors chaining is fine

Study case 2

We will modify the original Car class. Now, Car declare 5 fields and 3 constructors that have no relation between them.

1.Using constructor to value fields with default values is undesirable

As we don't value name and origin fields in their declaration and we have not a common constructor naturally invoked by other constructors, we are forced to introduce a initDefaultValues() method and invoke it in each constructor. So we have not to forget to call this method. Note that we could inline initDefaultValues() body in the no arg constructor but invoking this() with no arg from the other constructor is not necessary natural and may be easily forgotten :

2.Giving a default value in field initializers for fields which constructors don't assign to them a new value is fine

Here we don't need to have a initDefaultValues() method or a no arg constructor to call. Field initializers is perfect.

In any cases) Valuing fields in field initializers should not be performed for all fields but only for those that cannot be overwritten by a constructor.

Use case 1) In case of multiple constructors with common processing between them, it is primarily opinion-based. Solution 2 ( Using constructor to value all fields and relying on constructors chaining ) and solution 4 ( Giving a default value in field intializers for fields which constructors don't assign to them a new value and relying on constructors chaining ) appear as the most readable, maintainable and robust solutions.

Use case 2) In case of multiple constructors with no common processing/relation between them as in the single constructor case, solution 2 ( Giving a default value in field intializers for fields which constructors don't assign to them a new value ) looks better.

davidxxx's user avatar

I prefer field initializers and resort to a default constructor when there is complex initialization logic to perform (e.g. populate a map, one ivar depends on another through a series of heuristic steps to execute, etc).

@Michael B said:

... I'd prefer to put all initialization code into those (and chain them) rather than splitting it up between constructors and field initializers.

MichaelB (I bow to the 71+ K rep) makes perfect sense, but my tendency is to keep the simple initializations in the inline final initializers and do the complex part of the initializations in the constructor.

Bert F's user avatar

The only difference that I can think of is that if you were to add another constructor

then in the first example, you would no longer have a default constructor whereas in the 2nd example, you would still have the default constructor (and could even make a call to it from inside our new constructor if we wanted to)

Ojonugwa Jude Ochalifu's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged java oop constructor or ask your own question .

  • The Overflow Blog
  • If you want to address tech debt, quantify it first
  • Fighting comment spam at Facebook scale (Ep. 602)
  • Featured on Meta
  • Moderation strike: Results of negotiations
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Call for volunteer reviewers for an updated search experience: OverflowAI Search
  • Discussions experiment launching on NLP Collective
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Do position and spin commute?
  • Placement of surd with unicode-math is incorrect
  • Is "abreast a" something ever correct?
  • Noisy bottom bracket SHIMANO BB-RS500
  • Do exchange operators commute?
  • Which airline is liable for compensation in case of missed connection?
  • Do Catholic priests need permission from a bishop to retire?
  • 13 puzzles I like
  • Can we exchange logical disjunction for UNION ALL?
  • How do I cite development version of a software?
  • What makes a good alternative to flipping a coin for 50/50 randomness?
  • How to center in the definition context?
  • How to have my hair cut?
  • I've always learned that data standardization is not necessary for OLS regression, but then recommended for neural networks. Intuitively, why is that?
  • What are Non-GNU versions of terminal commands?
  • People who can't receive O negative blood?
  • What is the intent of Donald Trump's $200k bond?
  • Finding which process is reading from disk constantly on FreeBSD
  • How many days did it take for the Terminator to find real Sarah Connor?
  • Sustainable eating habits as a pilot
  • Roadmap for getting into a US graduate program in physics as an international student
  • Why are stars made from hydrogen and helium and not other elements?
  • Asymptotics for pairs of positive integers whose harmonic (resp. geometric) mean is an integer
  • Is there a socially-optimal way to drive on a busy interstate?

constructor assignment in java

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

IMAGES

  1. Java Constructor Tutorial

    constructor assignment in java

  2. What is the actual work of constructor in Java?

    constructor assignment in java

  3. Constructor in Java with Example

    constructor assignment in java

  4. Constructor in java

    constructor assignment in java

  5. Java

    constructor assignment in java

  6. Constructor in java

    constructor assignment in java

VIDEO

  1. Constructors program using java

  2. Constructor in java

  3. #022 constructors in java

  4. Constructors in Java

  5. Ch1_9-Java教學 建構子(Constructor) 1 使用基礎說明

  6. Java Class Object Constructor

COMMENTS

  1. Java Constructors - W3Schools

    A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes: Example Get your own Java Server Create a constructor:

  2. A Guide to Constructors in Java | Baeldung

    A Guide to Constructors in Java. 1. Introduction. Constructors are the gatekeepers of object-oriented design. In this tutorial, we'll see how they act as a single location from which ... 2. Setting Up a Bank Account. 3. A No-Argument Constructor. 4. A Parameterized Constructor. 5. A Copy ...

  3. Java Constructors - GeeksforGeeks

    Types of Constructors in Java. 1. Default Constructor in Java. A constructor that has no parameters is known as default the constructor. A default constructor is invisible. And if ... 2. Parameterized Constructor in Java. 3. Copy Constructor in Java.

  4. Best practices for assigning values passed through ...

    1 Yes (well, you could also use a Builder or a Factory pattern); but Java does not have Auto Implemented Properties. – Elliott Frisch Dec 9, 2017 at 22:07 So there is no way in Java to take the values passed in through the constructor and assign them in sequence to the class's variables? – Gary Holiday Dec 9, 2017 at 22:08 1

  5. Java Constructors (With Examples) - Programiz

    Java Constructors. 1. Java No-Arg Constructors. Similar to methods, a Java constructor may or may not have any parameters (arguments). If a constructor does not accept ... 2. Java Parameterized Constructor. 3. Java Default Constructor.

  6. Constructor in Java | DigitalOcean

    Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things - its name is the same as the class name and it has no return type. Sometimes constructors are also referred to as special methods to initialize an object.

  7. Constructors for Your Classes (The Java™ Tutorials ...">Providing Constructors for Your Classes (The Java™ Tutorials ...

    Providing Constructors for Your Classes. A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

  8. java - Default constructor vs. inline field initialization ...">java - Default constructor vs. inline field initialization ...

    5 Answers Sorted by: 113 Initialisers are executed before constructor bodies. (Which has implications if you have both initialisers and constructors, the constructor code executes second and overrides an initialised value)