836
Table of Contents
In this article you’ll learn about Methods in Java, Static Method, Static Block and The “finalize ()” method .
Methods
- A method is the block of code that can be called anywhere in a program. It contains a group of statements to perform an operation.
- Combination of method name and parameter is known as method signature.
- Required elements of method declaration are the method name, return type, a pair of parenthesis and body between braces {}.
Syntax
modifier returntype methodName (parameter)
{
// body
}
Example
public static int display (int a, String b)
{
//method body
}
where,
public static: modifiers
int: return type
display: method name
int a, String b: parameters
display (int a, String b): method signature
Example: Program for method
Program for swapping two numbers without using third variable.
class SwapNumber
{
public static void main(String[] args)
{
int n1 = 30;
int n2 = 45;
int temp;
System.out.println("Before swapping, n1 = " + n1 + " and n2 = " + n2);
swapMethod(n1, n2);
}
public static void swapMethod(int n1, int n2)
{
n1 = n1 + n2;
n2 = n1 - n2;
n1 = n1 - n2;
System.out.println("After swapping, n1 = " + n1 + " and n2 = " + n2);
}
}
Output:
Before swapping, n1 = 30 and n2 = 45 After swapping, n1 = 45 and n2 =30
Static Method
- When a method is declared with static keyword, it is known as a static method.
- A static method can be invoked without creating an object of the class.
- Static method belongs to class level.
Static Block
- Static block is also called as an initialization block.
- It is executed only once before main method at the time of class loading.
- A class can have any number of a static block.
Syntax:
class classname
{
Static
{
//code
}
}
Example: Sample program for static method
public class StaticMethod
{
static
{
System.out.println("First static block"); //static block
}
static void m1 ()
{
System.out.println("Static method");
}
void m2()
{
System.out.println("Non-static method");
}
Static
{
System.out.println("Second static block"); //static block
}
public static void main(String args[])
{
m1(); //invoked static method
StaticMethod sm = new StaticMethod();
sm.m2(); // invoked non static method
}
}
Output
First static block
Second static block
Static method
Non-static method
The “finalize ()” method
- Java runtime calls finalize () method when an object is about to get garbage collector.
- It is called explicitly to identify the task to be performed.
- The finalize() method is always declared as protected because it prevents access to the outside class.
Syntax
protected void finalize ()
{
// finalize code
}