bing
Flat 10% & upto 50% off + Free additional Courses. Hurry up!

static Keyword in Java

 

Static Variable: also known as Class Variables. Variables get default values based on datatypes. Static variable values are common for all objects of that class. That means if you are creating more than one object of a class that time also static variable is common for all variables. Memory allocation of static variable only happens once when the class is loading in memory. Declaration of static variable is

public class MyProgram1

{

static int a;

static int b;

public static void main(String[] arg)

{

System.out.pritnln("A value is:"+a);

System.out.println("B values is:"+b);

}

}

 

You can access these static variables in any other class using classname.

Int a= MyProgram1.a;

 

Static Method: Static methods can access class variables without using object of the class.  This static method can access non-static methods without object and non-static variables by using object of class. Let see the below example –

public class MyProgram1

{

public static void main(String[] arg)

{

staticMethod();

MyProgram1 obj=new MyProgram1();

obj.nonStaticMethod();

}

public static void staticMethod()

{

System.out.pritln("Static Method");

}

public void nonStaticMethod()

{

System.out.println("Non-Static Method");

}

}

 

Static Block: this static block will execute when class loaded in memory. A class can have multiple static blocks. Using this block we can change the default values of static variables. If we write multiple static blocks in a class it will execute as same sequence how you written into the program.

public class MyProgram1

{

static

{

System.out.println("Hello this is static block");

}

public static void main(String[] arg)

{

staticMethod();

MyProgram1 obj=new MyProgram1();

obj.nonStaticMethod();

}

public static void staticMethod()

{

System.out.pritln("Static Method");

}

public void nonStaticMethod()

{

System.out.println("Non-Static Method");

}

}

Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

"0 Responses on static Keyword in Java"

Training in Cities

Bangalore, Hyderabad, Chennai, Delhi, Kolkata, UK, London, Chicago, San Francisco, Dallas, Washington, New York, Orlando, Boston

100% Secure Payments. All major credit & debit cards accepted Or Pay by Paypal.

top

Sales Offer

  • To avail this offer, enroll before 10th December 2016.
  • This offer cannot be combined with any other offer.
  • This offer is valid on selected courses only.
  • Please use coupon codes mentioned below to avail the offer
offer-june

Sign Up or Login to view the Free static Keyword in Java.