Static and Non-Static Blocks Homework Help

What are Static and Non-Static Blocks in Java?

Use of static blocks:

In real-time scenarios, static blocks are used to provide information regarding the project before the actual project is executed.

Use of non-static blocks:

If we have many constructors in a class and if every constructor has some common statements, then instead of repeating those statements in each constructor, we place those statements in a non-static block. In this way, we can avoid duplication of the code.

Example of the program:

Class Bdemo1

{

Int I;

Bdemo1 ()

{

System. Out. Prinln (“inside the constructors “);

}

Static

{

 

 

System. Out. Prinln (“inside the static block “);

}

{

System. Out. Prinln (“inside the non- static block “);

}

Public static void main (string args [ ])

{

System. Out. Prinln (“inside the main “);

Bdemo1 b1 = new Bdemo1 ();

}

}

Output:

Inside the static block

Inside the main

Inside the non-static block

Inside the constructors.

An explanation for the output of the above program:

  1. As soon as JVM starts executing the .class file, it first creates a context of the class.
  2. Then all the static members of the class are loaded into the context.
  3. Now JVM searches for the main method once it finds the main method, it starts executing all the static blocks other than the main method. After that, it starts executing the main method.
  4. Inside the main method, we are creating an object of the class, JVM encounters the new operator, it reserves memory space in the RAM, i.e. creates the object, loads all the non-static members of the class into the object, initializes the uninitialized variables and then it loads the constructor.
  5. But after the creation of the object and before the loading of the constructor, it searches for non-static blocks. At this point in time, it executes all the non-static blocks and then loads and executes the constructor.

Static and Non-Static Blocks Homework Help

United States Get To Know Us Get in Touch   Tutoring Services   Top Subjects Test Prep
7740 McCallum Blvd, Dallas, TX About Us Contact Us   K-12 Tutoring   English Tutor GMAT Tutors
info@tutorspoint.com How It Works FAQ   Homework Help   Math Tutor LSAT Tutors
STUDENT SUPPORT Terms of Use Become a Tutor   Test Prep   Science Tutor SAT Tutors
support@tutorspoint.com Privacy Policy Students Blog   Assignment Help   Computer Tutor MCAT Tutors