adsense


Monday, 16 November 2015

JAVA HOME PAGE STATIC BLOCK PROGRAM PAGE 12








COMPUTER LANGUAGES HTML,C,C++.JAVA,.NET AND MULTIMEDIA basics and programs click home button



JAVA HOME PAGE STATIC BLOCK PROGRAM








Java static block program


Java programming language offers a block known as static which is executed before 
main method executes. Below is the simplest example to understand functioning of 
static block later we see a practical use of static block.

Java static block program
class StaticBlock {
  public static void main(String[] args) {
    System.out.println("Main method is executed.");
  }
 
  static {
    System.out.println("Static block is executed before main method.");
  }
}
Output of program:
 
Static block can be used to check conditions before execution of main begin, 
Suppose we have developed an application which runs only on Windows operating 
system then we need to check what operating system is installed on user machine. 
In our java code we check what operating system user is using if user is 
using operating system other than "Windows" then the program terminates.

class StaticBlock {
  public static void main(String[] args) {
    System.out.println("You are using Windows_NT operating system.");
  }
 
  static {
    String os = System.getenv("OS");
    if (os.equals("Windows_NT") != true) {
      System.exit(1);
    }
  }
}


No comments: