GoConqr hat ein neues Design! Sag uns, wie es dir gefällt.

Notizen

static block in java

varun taneja Englisch 1 Seite

Inhalt der Notizen (1)

Seite 1

unlike instance block, static block executes during dot class file loading

class file loads only once therefore static block runs only one time.

instance block executes for each instance of the class

A java class made up of following five components

class

{

1. variables (local, instance, static)

2. methods (instance, static)

3. constructors (default, user defined)

4. instance block

5. static block

}

static

{

//logics

}

like instance block , multiple static blocks are possible

upto jdk 1. 5 version, without main method , static block/s can be executed. But after 1. 5 version inside the class main is mandatory.

if we have three different class containing static block , then execte that static method we have two ways-----first one is that we can directly compile and execute (using cmd ) the each class but in this ways compiler needs the main in each classs--------in second method we dont need to define main in each class but only in one class, we can call the other classes which does not define main in the class which defines main using fornName method.

Example: -

class staticBlock

{

static

{

System.out.println("static block 1");

}

public static void main(String args[]) throws ClassNotFoundException

{

Class.forName("b");

Class.forName("c");

}

}

class b

{

static

{

System.out.println("static block b");

}

}

class c

{

static

{

System.out.println("static block c");

}

}

purpose of static block is to intialize static variables

Example: -

class staticBlock

{

static int eid;// defaul value will be 0

static

{

eid=222;// intialize eid during dot class loading

}

static void disp()

{

System.out.println(staticBlock.eid);

}

public static void main(String arg[])

{

staticBlock.disp();

}

}

Informationen

Beschreibung
Notiz am static block in java, erstellt von varun taneja am 16/11/2017.
Erstellt von
varun taneja
Aufrufe
0
Bewertung

Feedback

Worum geht es?

Wie gefällt dir das neue Design?

Dein Eindruck