Blocks in Java
Blocks are self executable.
Block has no name.
Block is used to perform some callback before initialized any thing.
Blocks are define inside class.
There are two types of blocks:
- Static Block
- Non-Static block
1. Static Block
class A{ static{ //static block } }
class A{ static{ System.out.println("static block"); } public static void main(String [] h){ } } //save and compile //javac A.java //run by //java A Output is : static block
class A{ static{ System.out.println("first static block"); } static{ System.out.println("second static block"); } }
class A{ static{ System.out.println("first static block"); } static{ System.out.println("second static block"); } public static void main(String [] h){ } } Output is : first static block Output is : second static block
2. Non-Static Block
class A{ { //non-static block } }
class A{ { System.out.println("non-static block"); } public static void main(String [] h){ new A(); } } Output is : non-static block
class A{ { System.out.println("first non-static block"); } { System.out.println("second non-static block"); } }
class A{ { System.out.println("first non-static block"); } { System.out.println("second non-static block"); } public static void main(String [] h){ new A(); } } Output is : first non-static block Output is : second non-static block
Some Examples :
class A{ static int i=10; static{ System.out.println(i); } public static void main(String [] h){ } } Output is : 10
class A{ static{ System.out.println(i); } static int i=10; public static void main(String [] h){ } } Output is : Compile time error /*In case of block variable must be declare first then use from any block*/
class A{ int i=10; static{ System.out.println(i); } public static void main(String [] h){ } } Output is : Compile time error
class A{ int i=10; { System.out.println(i); } public static void main(String [] h){ new A(); } } Output is : 10
class A{ static int i=10; { System.out.println(i); } public static void main(String [] h){ new A(); } } Output is : 10
class A{ { System.out.println(i); } static int i=10; public static void main(String [] h){ new A(); } } Output is : 10
No comments:
Post a Comment