Static Block
static block (also called static clause) which can be used for static initializations of a class. This code inside the static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class).
Instance Block
In a Java program, operations can be performed on methods, constructors and instance blocks.IIBs are executed before constructors. They run each time when an object of the class is created.
- Whenever class initialized and before constructors are invoked at that time instance blocks are executed.
- They are typically placed above the constructors within braces.
- It is not at all prime to include them in your classes.
Program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
package instanceBlock.com; import java.util.Scanner; /** * @author Kushal Thadani */ public class instanceBlocksWithMethod { int a , b; static int age; static String name; static String address; static String school; static String mobile_number; static Scanner block_obj = new Scanner(System.in); /** * @Instance Blocks * @method */ // Instance Block................. { System.out.println("Enter two integer number -:\n"); a = block_obj.nextInt(); b = block_obj.nextInt(); } // Second Instance Block of Strudent details....... static{ System.out.println("Enter Student Name -:\t"); name = block_obj.next(); System.out.println("Enter Student Age -:\t"); age = block_obj.nextInt(); System.out.println("Enter Student Home Address -:\t"); address = block_obj.next(); System.out.println("Enter Student School Name -:\t"); school = block_obj.next(); System.out.println("Enter Student Mobile Number-:\t"); mobile_number = block_obj.next(); } public void BlocksWithMethod(){ System.out.println("Student Name is -: \t" + name); System.out.println("Student Age is -: \t" + age); System.out.println("Student Address is -: \t" + address); System.out.println("School Name is -: \t" + school); System.out.println("Student Mobile Number is -: \t" + mobile_number); } // method to display values public void BlockMethod1(){ System.out.println("\n\n The value of A is = \t" + a); System.out.println("The value of B is = " + b + "\n\n"); } // Method calling within Constructor....... instanceBlocksWithMethod(){ BlockMethod1(); BlocksWithMethod(); } public static void main(String[] args) { // TODO Auto-generated method stub instanceBlocksWithMethod obj1 = new instanceBlocksWithMethod(); } } |