+ 5

What is the use of static block and constructor in java.

static block is used to execute a code(logic which u want to execute first with out using object) as soon as class is loaded. constructor is used to execute logic when object is created for that class.

20th Mar 2017, 7:15 PM
Pavan Kumar Basava
Pavan Kumar Basava - avatar
2 Antworten
+ 12
static block is similar for classes as constructors for objects. In a constructor you can initialize object properties, in a static block you can initialize class properties.
20th Mar 2017, 7:58 PM
Tamás Barta
Tamás Barta - avatar
+ 6
Static block executed once while class-loading or initialize by JVM. constructor executed every time while creating instance of that class. Here is the example. public class program { static{ System.out.println("Static block"); } program(){ System.out.println("Constructor"); } public static void main(String[] args) { program p1 = new program(); program p2 = new program(); } } Output: Static block Constructor Constructor
17th Jul 2017, 10:30 AM
Corey
Corey - avatar