Sunday, May 20, 2018

Define Static Keyword

Leave a Comment


Static Keyword in Java



static is a keyword and means ‘ can be accessed without the help of an object ‘.

static is used an access modifier with members ( variables and methods ) of class. A static member belongs to the whole class. That is, all the objects of the class share ( or access ) the same static variable. Or to say, a static variable is common to all the objects of the class. static variables do not have “this” reference. ‘ this ‘ is a keyword used to refer to a particular current object. This is quite contrast with instance variables where each variable keeps a separate copy of data when called with an object. The static variables like instance variables are given default values ( like zero for int ), if not assigned any values.



Declaring static members :

static int count ;

static int min( int a, int b)

{

//body

}

Static Keyword Example :

public class StaticDemo {
 static int salary = 5000;
 public static void display() {
  System.out.println("Hello");
 }
 public static void main(String args[]) {
  System.out.println(salary);

  //called directly without object
  StaticDemo sd = new StaticDemo();

  //called with object
  System.out.println(sd.salary);

  //called with class name
  System.out.println(StaticDemo.salary);

  //all the below display calls prints Hello

  display();
  sd.display();
  StaticDemo.display();
 }
}

Output :

double d = 10.5;
int x = d;
int y = (int) d;
System.out.println(y);

In the above, casting is done explicitly by us as we are assigning d of datatype double ( 8 bytes ) to x of datatype int ( 4 bytes ).
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment