0% found this document useful (0 votes)
21 views9 pages

Java Methods: Constructors & Destructors

The document discusses Java methods, constructors, and destructors. It explains what methods and constructors are, how to define and call methods, rules for writing constructors, and examples of using methods and constructors in Java code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views9 pages

Java Methods: Constructors & Destructors

The document discusses Java methods, constructors, and destructors. It explains what methods and constructors are, how to define and call methods, rules for writing constructors, and examples of using methods and constructors in Java code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Methods,Constructor,Destructor

A method is a block of statements under a name that gets executes only when it is called.
Every method is used to perform a specific task. The major advantage of methods is code re-
usability (define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means,
every method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.

returnType - Specifies the data type of a return value.


name - Specifies a unique name to identify it.
parameters - The data values it may accept or recieve.
{ } - Defienes the block belongs to the method

Creating a method
A method is created inside the class and it may be created with any access specifier. However,
specifying access specifier is optional.
Following is the syntax for creating methods in java.
Syntax

class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}}

The methodName must begin with an alphabet, and the Lower-case letter is preferred.
The methodName must follow all naming rules.
If you don't want to pass parameters, we ignore it.
If a method defined with return type other than void, it must contain the return statement,
otherwise, it may be ignored.

Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot
operator. It may call directly if the method defined with the static modifier. Every method call
must be made, as to the method name with parentheses (), and it must terminate with a
semicolon.
Syntax

<objectName>.<methodName>( actualArguments );
If the method has a return type, we must provide the receiver.
How can I write my first method?
Continuing the example of dividing two numbers, let's see how you can write a
method to divide two numbers. And how you can re-use it for various numbers.

Example: Method in Java


public class MethodsInJava {

public static int getQuotient(int dividend, int divisor) {


return dividend / divisor;
}

public static void main(String[] args) {


int x = 20, y = 2;
[Link]( x + " / " + y + " = " + getQuotient(x, y));

x = 30; y = 5;
[Link]( x + " / " + y + " = " + getQuotient(x, y));

x = 12; y = 6;
[Link]( x + " / " + y + " = " + getQuotient(x, y));

x = 45; y = 8;
[Link]( x + " / " + y + " = " + getQuotient(x, y));
}
}
Output
20 / 2 = 10
30 / 5 = 6
12 / 6 = 2
45 / 8 = 5

Explanation
public static int getQuotient(int dividend, int divisor) {

public is an access modifier. It means you can access this method (referred to
as function sometimes) outside the class MethodsInJava too.
The keyword static notifies that the method getQuotient can be called even
without creating an object of class MethodsInJava. This is a concept related to
object-oriented programming (you can skip it for now).
int is the return type of the method. This means, after executing the lines of
code, you can return an instance of any data type if you want to. Or keep it
void if not required. In this case, the product is returned of type int.
getQuotient the name of the method.
(int dividend, int divisor) are parameters passed to the method, of
type int. You can pass multiple parameters to a method according to your
requirements.
{ This curly brace marks the beginning of the method.
return dividend / divisor; } returns the quotient by dividing the given
parameters.
} marks the end of the method.
main() is the driver function where you can call the
method getQuotient(dividend, divisor) multiple times by-passing any two
integers of your choice. You can write the same method for other data types
like double, long etc too.
Print multiples of any integer
Let's look into another example of writing a method to find multiples of a
number.

Example: Method in Java

public class MultiplesUptoN {


public static void printFirstTenMultiples(int num) {
[Link]("Printing first 10 multiples of " + num);
for (int i = 1; i <= 10; i++) {
[Link](num + " x " + i + " = " + num*i);
}
}
public static void main(String[] args) {
// printing multiples of 2 different numbers
printFirstTenMultiples(5);
printFirstTenMultiples(3);
}
}
Output
Printing first 10 multiples of 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Printing first 10 multiples of 3
3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30

Example

import [Link];
public class JavaMethodsExample {
int sNo;
String name;
Scanner read = new Scanner([Link]);
void readData() {
[Link]("Enter Serial Number: ");
sNo = [Link](); //returns the int value scanned from the input.
[Link]("Enter the Name: ");
name = [Link]();
}
static void showData(int sNo, String name) {
[Link]("Hello, " + name + "! your serial number is " + sNo);
}
public static void main(String[] args) {
JavaMethodsExample obj = new JavaMethodsExample();

[Link](); // method call using object

showData(obj .sNo, [Link]); // method call without using object


}
}
OUTPUT
Enter Serial Number: 12
Enter the Name: subhash
Hello, subhash! your serial number is 12

Note:
Access_modifier static void methodName ()
{ // Method body.
}
The name of the class can be used to invoke or access static methods. The JVM runs the static method first, followed by the
creation of class instances. Because no objects are accessible when the static method is used.
A static method does not have access to instance variables.

//The next () method in java is present in the Scanner class and is used to get the input from the user. In order to use this
method, a Scanner object needs to be created.
This Java Scanner class method is used to scan the next token of the input as an int. This is an inbuilt method of Java Scanner
class which is used to scan the next token of the input as an int . It is used to interpret the token as a int value. The nextInt ()
method returns the int value scanned from the input

The objectName must begin with an alphabet, and a Lower-case letter is preferred.

The objectName must follow all naming rules.

Variable arguments of a method


In java, a method can be defined with a variable number of arguments. That means creating a method that receives any number of
arguments of the same data type.
Syntax

<returnType> <methodName>(dataType...parameterName);

Let's look at the following example java code.


Example

public class JavaMethodWithVariableArgs {


void diaplay(int...list) {
[Link]("\nNumber of arguments: " + [Link]);
for(int i : list) {
[Link](i + "\t");
}
}
public static void main(String[] args) {
JavaMethodWithVariableArgs obj = new JavaMethodWithVariableArgs();
[Link](1, 2);
[Link](10, 20, 30, 40, 50);
}
}

Constructors in Java
Constructor is a block of code that initializes the newly created object. A constructor
resembles an instance method in java but it’s not a method as it doesn’t have a return type. In
short constructor and method are different. People often refer constructor as special type of
method in Java.

Constructor has same name as the class and looks like this in a java code.

public class MyClass{


//This is the constructor
MyClass(){
}
..}
Let's look at the following example java code.

Note that the constructor name matches with the class name and it doesn’t have a
return type.

Rules for Writing Constructors

The Constructor name should match with the name of the class in which it resides.
In Java, the constructors can never be abstract, synchronized, static, and final.
It should not have any return type and value.
Constructors can have access modifiers to restrict their usage and for maintaining security.

How does a constructor work


To understand the working of constructor, lets take an example. lets say we have a
class MyClass.
When we create the object of MyClass like this:

MyClass obj = new MyClass()


The new keyword here creates the object of class MyClass and invokes the constructor to
initialize this newly created object.

You may get a little lost here as I have not shown you any initialization example, lets have a
look at the code below:
A simple Default constructor program in java
Here we have created an object obj of class Hello and then we displayed the instance
variable name of the object. As you can see that the output is [Link] which is what we have
passed to the name during initialization in constructor. This shows that when we created the
object obj the constructor got invoked. In this example we have used this keyword, which
refers to the current object, object obj in this example. We will cover this keyword in detail in
the next tutorial.

public class Hello {


String name;
//Constructor
Hello(){
[Link] = "[Link]";
}
public static void main(String[] args) {
Hello obj = new Hello();
[Link]([Link]);
}}
Output:

[Link]

no-arg constructor:
Constructor with no arguments is known as no-arg constructor. The signature is same as
default constructor, however body can have any code unlike default constructor where the
body of the constructor is empty.

Although you may see some people claim that that default and no-arg constructor is same but
in fact they are not, even if you write public Demo() { } in your class Demo it cannot be called
default constructor since you have written the code of it.

Example: no-arg constructor


class Demo{
public Demo()
{
[Link]("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}}
Output:
This is a no argument constructor

Parameterized constructor
Constructor with arguments(or you can say parameters) is known as Parameterized
constructor.

Example: parameterized constructor


In this example we have a parameterized constructor with two parameters id and name. While
creating the objects obj1 and obj2 I have passed two arguments so that this constructor gets
invoked after creation of obj1 and obj2.

public class Employee {

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
[Link] = id;
[Link] = name;
}
void info(){
[Link]("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
Employee obj3 = new Employee(10000,"PSIT");
[Link]();
[Link]();
[Link]();
} }
Output:

Id: 10245 Name: ChaitanyaId: 92232 Name: Negan


Example2: parameterized constructor
In this example, we have two constructors, a default constructor and a parameterized
constructor. When we do not pass any parameter while creating the object using new
keyword then default constructor is invoked, however when you pass a parameter then
parameterized constructor that matches with the passed parameters list gets invoked.

class Example2{
private int var;
//default constructor
public Example2()
{
[Link] = 10;
}
//parameterized constructor
public Example2(int num)
{
[Link] = num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example2 obj = new Example2();
Example2 obj2 = new Example2(100);
[Link]("var is: "+[Link]());
[Link]("var is: "+[Link]());
}}
Output:

var is: 10var is: 100

Example

public class ConstructorExample {


ConstructorExample() {
[Link]("Object created!");
}
public static void main(String[] args) {
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 = new ConstructorExample();
}
}

Output
Object created!
Object created!

What is a Destructor?

Destructors are typically used to deallocate memory. Also, they are used to clean up for objects and class members when the
object gets terminated.

Difference Between Constructor and Destructor in C++

[Link]. Constructors Destructors

1. The constructor initializes the class and allots the If the object is no longer required, then destructors
memory to an object. demolish the objects.

2. When the object is created, a constructor is called When the program gets terminated, the destructor is
automatically. called automatically.

3. It receives arguments. It does not receive any argument.

4. A constructor allows an object to initialize some of A destructor allows an object to execute some code at
its value before it is used. the time of its destruction.

5. It can be overloaded. It cannot be overloaded.

6. When it comes to constructors, there can be various When it comes to destructors, there is constantly a
constructors in a class. single destructor in the class.

7. They are often called in successive order. They are often called in reverse order of constructor.

What is the Method?


In the object-oriented programming world, a method is a grouping of instructions that execute some particular operation and
return the result to the caller. It helps the program to become more manageable. It allows us to reuse the code without writing it
again.

Difference between Constructor and Method

[Link]. Constructor Method

1. A constructor helps in initialising an object. A Method is a grouping of instructions that returns a


value upon its execution.

2. The new keyword plays a critical role in calling the Method calls play a critical role in invoking methods.
constructor.

3. It does not have a return type. It has a return type.

4. The name of the constructor and class will always be For the method, we can use any name.
the same.

5. A Constructor helps in initialising an object that A Method performs functions on pre-constructed or


doesn’t exist. already developed objects.

6. A class has the ability to have several constructors A class has the ability to have several methods with
with different parameters. different parameters.

7. It can’t be inherited by subclasses. It can be inherited by subclasses.

Common questions

Powered by AI

In Java, the lifecycle of an object begins with its creation using the `new` keyword, which allocates memory and invokes the constructor to initialize the object's state . After initialization, the object exists in the memory, capable of interacting and serving the program's logic through instance methods. Unlike C++, Java does not have destructors; instead, it relies on a garbage collector to deal with object cleanup once objects are no longer reachable or needed . The garbage collector automatically manages memory deallocation and ensures orphaned objects are removed, making destructor management unnecessary but necessitating mindful resource management and references to ensure timely collection .

Constructors in Java are special blocks of code used to initialize new objects; they do not have a return type and share the same name as the class . Methods, however, are used to group instructions that perform specific tasks and have a defined return type . Unlike constructors, methods can be inherited by subclasses and do not necessarily share a name with the class. Constructors are invoked automatically when an object is created using the 'new' keyword, while methods need to be explicitly called . These differences in initialization, inheritance, and invocation impact their usage, as constructors set up object states upon creation, while methods operate on existing objects to perform actions or calculations.

Static methods in Java belong to the class rather than any specific instance, allowing them to be called without creating an object of the class by using the class name . They do not have access to instance variables since they are not tied to any particular object state. Instance methods, on the other hand, require an object of the class to be created and can access instance variables . The implementation of static methods supports code that should be shared across all instances, such as utility functions, while instance methods are more suitable for handling operations that rely on the object's state, enhancing object-oriented design by encapsulating behaviors within objects .

Methods in Java facilitate code reusability by allowing developers to encapsulate code logic into named blocks that can be invoked as needed without repeating the code . Once defined, these methods can be reused across different parts of a program or even by different programs, improving efficiency and reducing redundancy. This practice not only saves time in development but also results in cleaner, more maintainable code, as changes to common logic need to be made only in one place rather than across multiple repeated code blocks .

Variable arguments, or varargs, in Java allow methods to accept zero or more arguments of the same type, using the syntax `type... parameterName` . This feature is particularly useful in scenarios where the exact number of arguments cannot be predetermined, such as aggregating data of similar types or performing operations on a set of inputs varying in size. Varargs enable the creation of flexible APIs that can handle multiple inputs with ease, reducing the need for multiple overloaded methods for varying parameter counts .

Encapsulation in Java refers to bundling the data (variables) and methods that operate on the data into a single unit, typically a class, and restricting direct access to some of the object's components . Methods play a crucial role in encapsulation by providing controlled access to an object's properties, allowing interaction with its state through defined interfaces while hiding implementation details. This mechanism not only safeguards an object's state but also maintains a clear separation between an object's internal states and the outside world, allowing developers to change the class's internal implementation without affecting the code that uses it .

Parameterized constructors in Java allow programmers to define multiple constructors with different parameters, enhancing flexibility by enabling objects to be initialized in different ways with specific values . This capability helps in reducing the need for additional methods to initialize objects after creation and promotes immutability by allowing flexible and precise object initialization during its instantiation phase. In application design, parameterized constructors facilitate the creation of distinct and well-defined instances of objects with required properties set at the moment of creation, thus simplifying the API and improving code clarity .

Access modifiers in method declarations, such as `public`, `protected`, `private`, and default (package-private), control the visibility of methods across different classes and packages . By setting appropriate access levels, developers can restrict the exposure of methods that should not be accessed or altered from outside the class or module. This enhances class security by protecting critical operations from unauthorized use and manipulation, ensuring that only intended parts of the codebase can interact with it. Moreover, access modifiers support encapsulation by defining clear interfaces for class interactions, promoting a coherent and maintainable design .

Method overloading allows developers to create multiple versions of a method within a class, each with different parameters, enabling flexibility in application design . By combining method overloading with access specifiers such as `public`, `protected`, and `private`, developers can control the visibility and accessibility of overloaded methods, ensuring that only appropriate versions are accessible based on the context. This combination enhances application robustness by providing tailored method versions for different needs while maintaining control over how these methods can be accessed, increasing security by ensuring that sensitive or critical logic is protected from unauthorized access .

Method overloading in Java occurs when multiple methods in the same class have the same name but different parameter lists (different types, number, or order of parameters). This allows a class to provide different implementations or adaptations of a method, enhancing program flexibility by enabling the method's action based on the input types. It supports polymorphism and improves code readability by maintaining consistent method names for conceptually similar operations meeting different contextual needs, thereby facilitating easier maintenance and a more intuitive API design .

You might also like