Since the string variable str is static, it is initialized to “This is second line displayed” (static variables are initialized before an object is initiated). Then, the static block is executed which will invoke the disp() method displaying the message: “This is first line displayed”. Static() method can be invoked without the need of any object. In main(), again disp() method is called with the string str (This is second line displayed). After that an object SMV is made, and it will get a member str2 initialized to “This is last line displayed”. Then disp() is called with SMV. str2 which displays: This is last line displayed on the screen
class StaticMethodVariable { static String str = "This is Second Line Displayed"; String str2 = "This is Last Line Displayed"; static { disp("This is First Line Displayed"); } public static void main(String[] args) { disp(str); StaticMethodVariable SMV = new StaticMethodVariable(); disp(SMV.str2); } static void disp(String str) { System.out.println(str); } }
Since the variables a and b are static! they are initialized to values 100 and 200 respectively (static variables are initialized before an object is initiated). Then, the static block is executed which will invoke the area() method with arguments a and b displaying the message: “Area of rectangle is 2000”. Static() method can be invoked without the need of any object. In main(), again area() method is called with the arguments a and b (Area of rectangle is 2000 will be displayed). After that an object k is made, and it will get a members c and d initialized to values 300 and 400 respectively. Then area() is called with SFV.c and SFV.d which displays: Area of rectangle is 12000 on the screen
/* Demonstration of Static Functions and Variables */
class StaticFunctionsVariables { static int a = 100; static int b = 200; int c=300; int d=400; static { area(a,b); } static void area(int x, int y) { System.out.println("Area of Rectangle is : "+x*y); } public static void main(String[] args) { area(a,b); StaticFunctionsVariables SFV = new StaticFunctionsVariables(); area(SFV.c, SFV.d); } }