How static keyword works in Java









Use   of   static   keyword .
-------------------------------------

Discussion  on static  keyword .   Here  is one of the  advantage uses  of the static keyword.

class  staticword{

static{

System.out.println("static block is invoked");  }


public static void main(String args[]){
System.exit(0);
System.out.println("Hello");
}


}



Output : -   static  block is invoked



class  statictest{


static{System.out.println("static block is invoked");

}
public static void main(String args[])
{
System.out.println("Hello main");
}
}

output --

Output:static block is invoked
Hello main
static block executes  first  before main.


This   program   will   explain  little bit   how   static   works .





class   stat
{

static  {

System.out.println("Hello first");

//printmethod2();  stat.java:8: error: non-static method printmethod2() cannot be referenced from a static context

}

public  static void main (String args[]){


printmethod();

System.out.println("Hello");
}

public static void printmethod(){
System.out.println("Hello Second");
}


public void printmethod2(){

System.out.println("Non Stat Mehtod");

}

}

Out put   of this  program  is  ..

Look  at  sequence  of the exceution
Hello first
Hello Second
Hello










--> -->
How static keyword works in Java How static  keyword  works in Java Reviewed by Mukesh Jha on 12:01 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.