Java (Notes 4) - Methods and Constructor

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Java Methods

● The method in Java or Methods of Java is a collection of statements that perform some
specific task and return the result to the caller.
● A Java method can perform some specific task without returning anything. Java Methods
allow us to reuse the code without retyping the code.
● In Java, every method must be part of some class.

1. A method is like a function i.e. used to expose the behavior of an object.


2. It is a set of codes that perform a particular task.

Syntax of Method
<access_modifier> <return_type> <method_name>( list_of_parameters){

//body
}

Example :
void addition1() {
int a=10;
int b=20;
System.out.println(a+b);
}
Types of Method
There are two types of methods in Java:

● Predefined Method
● User-defined Method

Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.

User-defined Method

The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
There are 2 types of User-defined Method

1. Static Method
2. Non-Static Method

Static Method

● A method that has static keyword is known as static method.


● In other words, a method that belongs to a class rather than an instance of a class
(object) is known as a static method.
● We can also create a static method by using the keyword static before the method name.
● The main advantage of a static method is that we can call it without creating an object.
● It can access static data members and also change the value of it.
● It is used to create an instance method. It is invoked by using the class name.
● The best example of a static method is the main() method.

Example :
static void addition1() {
int a=10;
int b=20;
System.out.println(a+b);
}
Instance (non-Static) Method
● The method of the class is known as an instance method.
● It is a non-static method defined in the class.
● Before calling or invoking the instance method, it is necessary to create an object of its
class.

Example :

void addition1() {
int a=10;
int b=20;
System.out.println(a+b);
}

Java Method With Parameters


In Java, parameters and arguments are related concepts used in method declarations and
method calls, respectively.

Parameters:

1. Parameters refer to the variables declared in the method signature, inside the parentheses,
to receive values from the caller.
2. They define the input that a method expects when it is called.
3. Parameters are local variables within the method and are used to perform operations or
calculations within the method's body.

Here's an example of a method declaration with parameters:


public static void printName(String name) {
System.out.println("Hello, " + name + "!");
}

In the above example, name is the parameter of the method printName(). It specifies that the
method expects a String argument to be passed when calling the method.

Arguments:
● Arguments are the actual values passed to a method when it is called. They are the
concrete values that are assigned to the parameters of the method.
● Arguments can be literals, variables, or expressions.
● Using the same method example as above, let's see how arguments are used:

printName("John");

In the method call printName("John"), "John" is the argument.


It is the actual value that will be assigned to the name parameter of the printName() method.

Here's an example to demonstrate a method called calculateSum that takes two integers as
parameters and returns their sum:

public int calculateSum(int num1, int num2) {


int sum = num1 + num2;
return sum;
}

In the example above, the method calculateSum has an access modifier public, a return type of
int, and two parameters num1 and num2, both of type int.
It calculates the sum of the two numbers and returns the result as an int value.
You can call this method by passing the required arguments, like so:

int result = calculateSum(5, 3);


System.out.println(result); // Output: 8

Here, 5 and 3 are the actual arguments being passed to the calculateSum method, and the
returned value 8 is stored in the variable result. Finally, the result is printed, displaying the
sum of the two numbers.

Constructor in Java
● In Java, a constructor is a special method that is used to initialize objects of a
class.
● It is called when an instance (object) of a class is created using the new
keyword.
● The primary purpose of a constructor is to set initial values for the instance
variables of the object being created.
Here are some key points about Java constructors:

1. Constructor Naming: Constructors have the same name as the class they belong to.
They do not have a return type, not even void.
2. Initialization: Constructors are responsible for initializing the state of the object. They
can initialize instance variables, perform calculations, allocate memory, or execute any
other necessary setup tasks.
3. Automatic Invocation: A constructor is automatically called when an object is created
using the new keyword. It ensures that the object is properly initialized before it can be
used.
4. Overloading: Constructors can be overloaded, which means a class can have multiple
constructors with different parameters. This allows objects to be created with different
initialization based on the arguments provided.
5. Default Constructor: If a class does not explicitly define any constructors, a default
constructor is provided by Java. This default constructor has no parameters and performs
no explicit initialization. However, if you define any constructor explicitly, the default
constructor is not automatically provided.

Here's an example of a class with a constructor:


public class Person {
private String name;
private int age;

// Constructor with parameters


public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Constructor with no-parameters


public Person() {

System.out.println("no-paramters Constructor");

Here's how you can create a Person object using the constructor:
Person person = new Person("John", 25);

In this code, the new Person("John", 25) statement creates a new Person object and invokes
the constructor with the arguments "John" and 25.

Constructors play a crucial role in object initialization and provide a way to ensure that objects
are properly set up before they are used in a program.
Method vs Constructor
Constructors Methods
Purpose Initialize objects Define behavior or actions
User-defined, can have any
Name Same as the class name
valid identifier
Can have any valid return
Return Type No return type (not even void)
type, including void
Automatically invoked during object Explicitly invoked by method
Invocation
creation call
Constructors can be overloaded with Methods can be overloaded
Overloading
different parameter lists with different parameter lists
Parameters Can have parameters Can have parameters
Accessibili Can have access modifiers (public, Can have access modifiers
ty private, etc.) (public, private, etc.)
Not inherited (but super class
Inherited by subclasses
Inheritance constructors can be invoked using
(unless overridden)
super)
Perform operations,
Usage Create and initialize objects
calculations, or actions

You might also like