Static Keyword: Dr. Sapna Malik Assistant Professor, MSIT
Static Keyword: Dr. Sapna Malik Assistant Professor, MSIT
10
A static block-Advantages
If the driver or other items need to be loaded into the
namespace ,then static block may be used.
If computation is needed to be done to initialize the static
block can be declared which gets exactly once ,when the
class is first loaded.
It handles security related issues or logging related tags.
11
A static block-Limitation
JVM has a limitation that static block should not exceed
64k.
Checked exception can not be thrown in static blocks.
Exception can be handled with try catch block for static
block.
This and super keywords can not be used I static blocks
Static block can not be declared inside method.
12
A static block-Example 1
class Demotry {
static{
System.out.println("i am in static block");
int a=2,b=3,c=0;
c=a+b;
System.out.println("c= "+c);
}
Demotry(){
System.out.println("i am in constructor ");
}
public static void main(String[] args){
Demotry d = new Demo();
}
static {
System.out.println("i am in second static block");
}
}
Output:
i am in static block
C=5
i am in second static block
i am in constructor
13
A non static block/Constructor block
Non Static block/constructor block are the normal block
without any preceding.
Syntax
{
//Java Codes
}
Non Static block is executed for each object that is
created.
It can initialize instance variable in a class.
Non static blocks will be copied into each constructor of
the class.
14
A non static block/Constructor block
Example
class Demotry1 {
{
System.out.println("i am in non static block/constructor block");
}
Demotry1(){
Output:
System.out.println("i am in constructor"); i am in static block
} i am in non static
Demotry1(int d){ block/constructor block
System.out.println("i am in parameterized constructor");
i am in second non static
block/constructor block
}
i am in constructor
public static void main(String[] args){ i am in non static
Demotry1 c=new Demotry1(); block/constructor block
Demotry1 d=new Demotry1(5); i am in second non static
block/constructor block
}
i am in parameterized constructor
static{
System.out.println("i am in static block");
}
{
System.out.println("i am in second non static block/constructor block");
}
15 }
Method Overloading
If a class has multiple methods having same name but
different in parameters, it is known as Method
Overloading.
Method overloading increases the readability of the
program.
There are two ways to overload the method in java
o By changing number of arguments
o By changing the data type.
Method Overloading is not possible by changing the
return type of the method only.
16