static keyword
We can apply on
- Variables
- methods
- blocks
1. static variables :
- static variables is the common property for all objects of the class.
- At the time of class loading memory will be allocated for static variables.
syntax:
class classname
{
static variables;
}
class classname
{
static variables;
}
-------------------------------------------------------------------
Program : static variables
Program name : RecordDemo1.java
Output :
Roll No:1
Name:Nani
College Name:Newtons college
Roll No:2
Name:Naveen
College Name:Newtons college
class RecordDemo1
{
int rollNo ;
String name ;
static String collegeName = "Newtons college";
RecordDemo1(int r, String n)
{
rollNo = r;
name =n;
}
public void details()
{
System.out.println("Roll No:"+rollNo);
System.out.println("Name:"+name);
System.out.println("College Name:"+collegeName);
}
public static void main(String args[])
{
RecordDemo1 r1 = new RecordDemo1(1,"Nani");
RecordDemo1 r2 = new RecordDemo1(2,"Naveen");
r1.details();
r2.details();
r2.details();
}
}
Compile : javac RecordDemo1.java
Run : java RecordDemo1
Output :
Roll No:1
Name:Nani
College Name:Newtons college
Roll No:2
Name:Naveen
College Name:Newtons college
-------------------------------------------------------------------
2. static methods
- If we find any method declaration with static keyword then we can say it is static method.
- We can call static methods by using class name, so object is not required to call static methods.
class classname
{
static returntype methodName1()
{
body of the static method;
}
}
{
static returntype methodName1()
{
body of the static method;
}
}
-------------------------------------------------------------------
Program : static method
Program name : Demo2.java
Output :
Its a static method
class Demo2
{
public static void m1()
{
System.out.println("Its a static method");
}
public static void main(String args[])
{
Demo2.m1();
}
}
Compile : javac Demo2.java
Run : java Demo2
Output :
Its a static method
-------------------------------------------------------------------
3 static block
- we can initialize the static variables here.
- static block will execute before main method.
- static data will be set right at the time of class loading only
-------------------------------------------------------------------
Program : Static block
Program name : Demo2.java
Output :
Its a static block
class Demo2
{
static
{
System.out.println("Its a static block");
}
public static void main(String args[])
{
}
}
Compile : javac Demo2.java
Run : java Demo2
Output :
Its a static block
-------------------------------------------------------------------
Without main method
- We can define a program without main method but it is possible only in below versions of 1.7.
-------------------------------------------------------------------
Thanks for your time.
Thanks for your time.
Nireekshan