Java Methods
A method
in Java is a block of code that
performs a specific task and executes only when it is called
(invoked).
It helps in reusing code by defining
a logic once and calling it multiple times whenever required.
Methods are also known as functions in other programming languages such as C or C++.
Purpose of Methods
The main goals of using methods in Java are:
Perform specific tasks: Each method handles one defined operation, like calculation or displaying data.
Avoid code repetition: The same logic can be reused by calling the method instead of rewriting it.
Make programs modular and readable: Dividing a program into smaller methods makes it easier to understand and debug.
Improve code reusability: Once defined, a method can be used in different parts of the program or other classes.
Types of Methods in Java
There are two main types of methods:
1. Predefined Methods (Built-in Methods)
2.
User-defined Methods
3.
1. Predefined Methods
These are methods already defined
and available in Java libraries.
Programmers can use them directly without creating them manually.
Examples:
·
System.out.println() — prints text on
the console.
·
Math.sqrt(16) — returns the square
root of a number.
·
length() — returns the length of a
string or array.
Example Code:
public class Example1 { public static void main(String[] args) { System.out.println("Hello, this is a predefined method!"); double result = Math.sqrt(25); System.out.println("Square root of 25 is: " + result); }}
Output:
Hello, this is a predefined method!Square root of 25 is: 5.0
2. User-defined Methods
These are methods that the
programmer creates to perform specific actions.
They can accept inputs (parameters) and
may or may not return a value.
General Syntax of a Method
returnType methodName(parameters) { // body of the method // statements to execute}
Explanation of Each Part:
|
Part |
Description |
|
returnType |
Specifies what type of value
the method returns (e.g., |
|
methodName |
The name of the method (should
follow Java naming conventions). |
|
parameters |
The list of input values
(optional). They are declared within parentheses. |
|
method
body |
The block of code that performs
the task when the method is called. |
:
Basic method and Calling a Method
To call or execute a method, use
its name followed by parentheses () and a semicolon.
Example:
public class Main { static void myMethod() { System.out.println("Hello! Method is running."); } public static void main(String[] args) { myMethod(); // calling the method }}
Output:
Hello! Method is running.
· myMethod() → The name of the method.
· static → It belongs to the class and can be called without creating an object.
· void → It does not return any value.
·
The code inside {} runs when the
method is called.
Examples of
User-defined Methods
Example 1: Method Without Arguments and Without Return Type
This type of method does not take any input and does not return any value.
public class Main { static void Method1() { int l = 20, b = 40; int area = l * b; System.out.println("Area: " + area); } public static void main(String[] args) { Method1(); // calling the method }}
Output:
Area: 800
Example 2: Calling a Method Multiple Times
You can call a method as many times as needed.
public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); myMethod(); myMethod(); }}
Output:
I just got executed!I just got executed!I just got executed!
Example 3: Method With Arguments
(Parameters)
This type of method takes input values but does not return anything.
public class Main { static void Method1(int l, int b) { int area = l * b; System.out.println("Area: " + area); } public static void main(String[] args) { int l = 20, b = 40; Method1(l, b); // passing arguments }}
Output:
Area: 800
Example 4: Method With Return Type
A method can return a value to the place where it is called.
public class Main { static int square(int x) { return x * x; // returns the square of the number } public static void main(String[] args) { int result = square(5); System.out.println("Square of 5 is: " + result); }}
Output:
Square of 5 is: 25
Constructor
A constructor in Java is a special block of code that:
- Has the same name as the class.
- Is automatically called when an object is created.
- Is used to initialize objects (assign initialvalues to variables).
- Does not have any return type, not even void.
- A constructor is called when you create an object using new keyword.
- Student s1 = new Student(); // constructor is called here
- If no constructor is defined, Java automatically provides a default constructor.
- It is called constructor because it "constructs" the object’s data during creation.
Rules for Creating a Constructor
- The constructor name must match the class name.
- A constructor cannot have a return type.
- A constructor cannot be abstract, static, final or synchronized.
- Access modifiers (public, private, protected, defaul can control where the constructor is accessible.
Types of Java constructors
There are two types of constructors in Java:
- Default constructor (no-arg constructor)
- Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
<class_name>(){}
Example of default constructor
In this example, we
are creating the no-arg constructor in the Bike class.
It will be invoked at
the time of object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
In this example, we are creating the no-arg constructor in the
Bike class.
It will be
invoked at the time of object creation.
//Java Program to create and call a default
constructor
class Bike1{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler
automatically creates a default constructor.
Java Parameterized
Constructor
A parameterized constructor is
a constructor that includes one or more parameters.
It is used to initialize objects with specific values during their creation.
By using parameterized constructors, we can assign different values to
different objects — although
the same values can also be
used if desired.
Key
Points:
· The
constructor has parameters that accept values when creating an object.
· It
allows initialization of object properties at the time of object creation.
· You
can create multiple objects with different data using the same constructor.
· The
constructor name must be same
as the class name.
Example:
Java Program to Demonstrate Parameterized Constructor
// Java Program to demonstrate the use of parameterized constructorclass Student4 {
int id;
String name;
// Creating a parameterized constructor
Student4(int i, String n) {
id = i;
name = n;
}
// Method to display the values
void display() {
System.out.println(id + " " + name);
}
public static void main(String args[]) {
// Creating objects and passing values
Student4 s1 = new Student4(1, "Aakirti");
Student4 s2 = new Student4(2, "Ayusha");
// Calling method to display the values of objects
s1.display();
s2.display();
}
}
Output:
1 Aakirti
2 Ayusha
Difference between constructor and method
Java
Constructor
Java
Method
A
constructor is used to initialize the state of an object.
A
method is used to expose the behavior of an object.
A
constructor must not have a return type.
A
method must have a return type.
The
constructor is invoked implicitly.
The
method is invoked explicitly.
The
Java compiler provides a default constructor if We don't have any
constructor in a class.
The
method is not provided by the compiler in any case.
The
constructor name must be same as the class name.
The
method name may or may not be same as the class name.
Comments
Post a Comment