JAVA STATIC FUNCTIONS
Ø What are static
function ?
Static methods are the methods which are declare in static keyword
these methods are not dependent on objects i.e., they are called directly in a
class.
// Java program to call a
static method
class GFG {
//
static method
public static int sum(int a, int b)
{
return a + b;
}
}
class Main {
public static void main(String[] args)
{
int n = 3, m = 6;
//
call the static method
int s = GFG.sum(n, m);
System.out.print("sum
is = " + s);
}
}
Output:
sum is = 9
Ø What are non- static function?
Non-static function which dosen’t required any
keyword to declare these function must be called by an function these function
are dependent on objects for calling.
Java program to call a
non-static method
class GFG {
Java
program to call a non-static method
class GFG
// non-static method
public int sum(int a, int b)
{
return a + b;
}
}
class Main {
public static void main(String[] args)
{
int n = 3, m = 6;
GFG
g = new GFG();
int s = g.sum(n, m);
//
call the non-static method
System.out.print("sum
is = " + s);
}
}
Output:
sum is = 9
Uses
of keyword in program :-
· Static- use without object .
· Public-
acess modifier which make sure main() can be used anywhere in the program.
· Void:- Main function well not return any
value.
· Main:- First method to be excuted in java
application .
· String:- It’s a class.
· args[]
- array of string type .
Difference
table:
POINTS |
STATIC METHOD |
NON-STATIC
METHOD |
Definition |
A static method is a method
that belongs to a class, but its not belongs to an instance of that class and
this method can be called without the instance or object of that class. |
Every
methods in java are non-static method, but the methods must not have static keyword before
method name. non-static methods
can access any static method
and static variable also,
without using the object of the class. |
Accessing members and methods |
In static method, the method
can only access only static data members and static methods of another class
or same class but cannot access non-static methods and variables. |
In non-static method, the
method can access static data members and static methods as well as
non-static members and method of another class or same class. |
Binding process |
Static method uses compile time or early binding. |
Non-static method uses runtime or dynamic binding. |
Overriding |
Static method cannot be overridden because of
early binding. |
Non-static method can be overridden because of runtime
binding. |
Memory allocation |
In static method, less memory
is use for execution because memory allocation happens only once, because the
static keyword fixed a particular memory for that method in ram. . |
In non-static method, much
memory is used for execution because here memory allocation happens when the
method is invoked and the memory is allocated every time when the method is
called. |
HOW
TO EXECUTE & RUN THE CODE
OUTPUT |
JVM |
eg.java |
Comments
Post a Comment