Methods & Constructor in Java

Yuvaraj
8 min readFeb 3, 2023

--

Methods and Constructor in Java

Method

A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. Ypu can pass data, known as parameters, into a method and method is also known as functions.

Method Declaration

To create a method, it must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions.

The method declaration provides information about method attributes such as visibility, return type, name, and arguments. It has six components that are known as the method header.

Method Declaration

In general, method declarations has these components :

  1. Access Modifier: It defines the access type of the method. i.e. from where it can be accessed in your application. In Java, there are four types of access modifiers.
  • public: accessible in all class in your application.
  • protected: accessible within the class in which it is defined and in its subclass(es)
  • private: accessible only within the class in which it is defined.
  • default :(declared/defined without using any modifier) : accessible within same class and package within which its class is defined. (To know more about access modifiers, click here.)

2. The return type is the data type of the value returned by the method, or void if it does not return a value.

3. Method Name: The rules for field names apply to method names as well, but the convention is a little different.

4. Parameter list: A comma-separated list of the input parameters is defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ( ).

5. Exception list: The exceptions you expect by the method can throw, you can specify these exception(s).

6. Method body: It is enclosed between braces. The code that must be executed in order to carry out your intended operations.

7. Method Signature: Every method has a method signature. It is part of the method declaration. It includes the method name and parameter list.

public class Main {
static void myMethod() {
// code to be executed
}
}

In this example,

  • myMethod() is the name of the method.
  • static means that the method belongs to the Main class and is not an object of the Main class.
  • void means that this method does not have a return value.
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String args[]) {
myMethod();
}
}

// Output: I just got executed!

Here, to call a method in Java, write the method’s name followed by two parentheses () and a semicolon ;

Since it is a static method, we do not need to create an object to call the method.

Types of Method

  1. Predefined Method: predefined methods are the methods that is already defined in the Java class libraries is known as predefined method or built-in method. We can directly use these methods just by calling them in the program at any point. Ex: length(), equals(), compareTo(), sqrt().
public class Main {
public static void main(String[] args) {
// using the sqrt() method
System.out.println("Square root of 4 is: " + Math.sqrt(4));
}
}

// Output: 2

2. User-Defined Method: The method written by the user or programmer is known as a user-defined method. Ex: isSmartCoder();

// Addition of two numbers

public class Addition {

static void main(String[] args) {
int a = 10;
int b = 5;
int c = add(a, b);
System.out.println("The sum of a and b is = " + c);
}

//user defined addition method
static int add(int num1, int num2) {
int sum;
sum = num1 + num2;
return sum; //returning the sum
}
}

// Output: The sum of a and b is = 15

Static Method

A static method is a method that belongs to a class rather than an instance of a class. This means you can call a static method without creating an object of the class. We can also create a static method by using the keyword static before the method name. It is also used for memory management.

Instance Method

Instance methods are the methods that require an object of their class to be created before they can be called. To invoke an instance method, we have to create an object of the class in which the method is defined. The method of the class is known as an instance method. It is a non-static method defined in the class.

Method Calling

class Main {
// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
return sum; // return value
}

public static void main(String[] args) {
int num1 = 25;
int num2 = 15;
Main obj = new Main(); // create an object of class (Main)
int result = obj.addNumbers(num1, num2); // calling method
System.out.println("Sum is: " + result);
}
}

// Output: Sum is: 40

Here, we have declared a method named addNumbers( ). Now, to use the method, we need to call it. When you call the function as shown the in the above example. The control is transferred from the main() function to the addNumbers() function. The addNumbers() function performs operation i.e. to sum(add) the a (num1) and b (num2) values. Now as the the function reaches the last statement which is a return statement, it returns the control back to the main function while returning the sum value (in this case 40).

Method Return Type

class Main {
// crate a method
public static int square(int num) {
// return statement
return num * num;
}

public static void main(String[] args) {
int result;
// call the method
// store returned value to result
result = square(10);
System.out.println("Squared value of 10 is: " + result);
}
}

// Output: Squared value of 10 is: 100

A Java method may or may not return a value to the function call. We use the return statement to return any value.

Method Parameters

// method with two parameters
int addNumbers(int a, int b) {
// code
}

// method with no parameter
int addNumbers() {
// code
}
class Main {
// method with no parameter
public void display1() {
System.out.println("Method without parameter");
}

// method with single parameter
public void display2(int a) {
System.out.println("Method with a single parameter: " + a);
}

public static void main(String[] args) {
Main obj = new Main(); // create an object of Main
obj.display1(); // calling method with no parameter
obj.display2(24); // calling method with the single parameter
}
}

// Output: Method without parameter
Method with a single parameter: 24

Advantages of using methods

The main advantage is code reusability. We can write a method once and use it multiple times. We do not have to rewrite the entire code each time.

  • Methods make code more readable and easier to debug. For example, add2Numbers() method is so readable, that we can know what this method will be performing addition of 2 numbers.

Constructor

In Java, a constructor is a special type of method that is called when an instance of object is created and memory is allocated for the object. It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn’t have any.

Every time an object is created using the new() keyword, at least one constructor (it could be default constructor) is called.

public class ConstructorExample {
ConstructorExample() {
// Body of Constructor
}

public static void main(String[] args) {
// Invoking Constructor
ConstructorExample obj = new ConstructorExample();
}
}

Rules for Creating a Constructor

  • Constructor name must be the same as its class name.
  • There is no return type in a constructor.
  • A Java constructor cannot be abstract, static, final, and synchronized.
  • An interface cannot have the constructor.
  • Constructors cannot be private.
  • A constructor can be overloaded.
  • An abstract class can have the constructor.
  • Constructors are automatically called when an object is created.
  • Constructors cannot return a value.

There are two types of constructor in Java:

  • Default constructor (no-arg constructor)
  • Parameterized constructor

Default Constructor

A constructor that has no parameters is known as default constructor. Default constructor is mostly use to initialize the default values for the class fields. If we don’t define a constructor in a class, then compiler creates default constructor(with no arguments) for the class.

public class ConstructorExample {
// Default Constructor
ConstructorExample() {
System.out.println("Default Constructor");
}

public static void main(String[] args) {
// Constructor Called
ConstructorExample obj = new ConstructorExample();
}
}

// Output: Default Constructor

In the example above, you can see that the default constructor is called when the object is instantiated using the new keyword. Thus the constructor is used to construct the values of objects.

Parameterized constructor

A constructor which has a specific number of parameters is called a parameterized constructor. The main aim to create parameterized constructor is to initialize the objects with programmer-defined states or values. If we want to initialize fields of the class with your own values, then use parameterized constructor.

class Example{
//Default constructor
Example(){
System.out.println("Default constructor");
}
/* Parameterized constructor with
* two integer arguments
*/
Example(int i, int j){
System.out.println("constructor with Two parameters");
}
/* Parameterized constructor with
* three integer arguments
*/
Example(int i, int j, int k){
System.out.println("constructor with Three parameters");
}

/* Parameterized constructor with
* two arguments, int and String
*/
Example(int i, String name){
System.out.println("constructor with int and String param");
}
public static void main(String args[]){
//This will invoke default constructor
Example obj = new Example();

/* This will invoke the constructor
* with two int parameters
*/
Example obj2 = new Example(12, 12);

/* This will invoke the constructor
* with three int parameters
*/
Example obj3 = new Example(1, 2, 13);

/* This will invoke the constructor
* with int and String parameters
*/
Example obj4 = new Example(1,"MediumBlog");
}
}

/* Output:
Default constructor
constructor with Two parameters
constructor with Three parameters
constructor with int and String param */

In this example, I have implemented four constructors: one is default constructor and other three are parameterized. You can see the parameterized constructor is called when we pass a value in the opening and closing parentheses.

Advantages:

  • Reusability: We can create multiple objects with different initial values.
  • Support for inheritance: It is useful for inheritance where subclasses can extend the constructors of their super classes.
class Example{
Example(int i, int j){
System.out.print("parameterized constructor");
}
Example(int i, int j, int k){
System.out.print("parameterized constructor");
}
public static void main(String args[]){
Example obj = new Example();
}
}

/* Output:
Exception in thread "main" java.lang.Error: Unresolved compilation
problem: The constructor Example() is undefined */

The program throw compilation error because the statement Example obj = new Example(); is trying to invoke the default constructor (no argument constructor) which we don’t have in our program. You don’t get this error if you remove the parameterized constructors from the above code.

A class can have multiple constructor with different no of method arguments, which is also called “constructor-overloading

Difference between method and constructor

Copy Constructor

Java does not have a built-in copy constructor. Java does not provide this feature natively.

However, developers can create their own copy constructor in Java by writing a constructor that takes an object of the same class as its argument and copies its state to a new object.

This approach requires manual implementation, unlike in some other languages, where the copy constructor is generated automatically.

--

--