S. M. Shamim, Dept.
of ICT, MBSTU
Java Static Keyword
TU
The static keyword in java is used for memory management mainly.
Static keyword can be used with class, variable, method and block.
Static members belong to the class instead of a specific instance, this means if you make a
member static, you can access it without object.
BS
The static can be:
o variable (also known as class variable)
o method (also known as class method)
M
o block
o nested class
T,
Java Static Variables
The static variable can be used to refer the common property of all objects
f IC
A static variable is common to all the instances (or objects) of the class because it is a class level
variable.
The static variable gets memory only once in class area at the time of class loading.
It makes your program memory efficient (i.e it saves memory).
t. o
Only a single copy of static variable is created and shared among all the instances of the class.
Memory allocation for such variables only happens once when the class is loaded in the
memory.
Static variables are also known as Class Variables.
ep
Unlike non-static variables, such variables can be accessed directly in static and non-static
methods.
Example-1:
,D
Suppose there are 500 students in my college, now all instance data members will get memory each
time when object is created. All student has its unique rollno and name so instance data member is
good. Here, college refers to the common property of all objects. If we make it static, this field will
im
get memory only once.
class Student{ void display ( ) {
am
int rollno; System.out.println(rollno+" "+name+"
String name; "+college);}
static String college ="ITS";
public static void main(String args[]){
Sh
Student(int r, String n){ Student s1 = new Student8(111,"Karan");
rollno = r; Student s2 = new Student8(222,"Aryan");
name = n;
} s1.display();
M.
s2.display();
}
}
S.
Output:111 Karan ITS
222 Aryan ITS
S. M. Shamim, Dept. of ICT, MBSTU
Example-2:
In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each
TU
objects will have the value 1 in the count variable.
#with statc and without static count
BS
class Counter{
int count=0; public static void main(String args[]){
M
Counter(){ Counter c1=new Counter();
count++; Counter c2=nw Counter();
System.out.println(count); Counter c3=new Counter();
T,
} }
}
Output: 1 1 1
f IC
Java static method
If we apply static keyword with any method, it is known as static method.
t. o
A static method belongs to the class rather than object of a class.
Static Methods can access class variables (static variables) without using object of the class,
However non-static methods and non-static variables can only be accessed using objects.
Static methods can be accessed directly in static and non-static methods.
ep
static method can access static data member and can change the value of it.
The static method cannot use non static data member or call non-static method directly.
this and super cannot be used in static context.
,D
Java main method is static because object is not required to call static method if it were non-static
method, jvm create object first then call main() method that will lead the problem of extra
memory allocation.
im
Example-1
class JavaExample{ Example-2
static int i = 10; class JavaExample{
am
static String s = "book"; static int i = 100;
//This is a static method static String s = " book ";
public static void main(String args[]) static void display()
{ {
Sh
System.out.println("i:"+i); System.out.println("i:"+i);
System.out.println("s:"+s); System.out.println("i:"+s);
} }
} void funcn()
M.
Output: i:10 { display(); }
s:book public static void main(String args[])
{
S.
JavaExample obj = new JavaExample();
obj.funcn();
display(); } }
S. M. Shamim, Dept. of ICT, MBSTU
Java static block
Static block is used for initializing the static variables.
This block gets executed when the class is loaded in the memory.
A class can have multiple Static blocks, which will execute in the same sequence in which they
TU
have been written into the program.
Example-1
BS
class JavaExample{
static int num Example-3
static String mystr; class JavaExample2{
M
static{ static int num;
num = 97; static String mystr;
mystr = "Static keyword in Java"; //First Static block
T,
} static{
public static void main(String args[]) System.out.println("Static Block 1");
f IC
{ num = 68;
System.out.println("Value of num: "+num); mystr = "Block1";
System.out.println("Value of mystr: "+mystr); }
} //Second static block
} static{
t. o
Output: System.out.println("Static Block 2");
Value of num: 97 num = 98;
Value of mystr: Static keyword in Java mystr = "Block2";
ep
}
Example-2 public static void main(String args[])
class A2{ {
,D
static{ System.out.println("Value of num: "+num);
System.out.println("static block invoked"); System.out.println("Value of mystr: "+mystr);
} }
im
public static void main(String args[]){ }
System.out.println("Hello main");
} Output: Static Block 1
am
} Static Block 2
Output: Value of num: 98
static block is invoked Value of mystr: Block2
Hello main
Sh
M.
S.
S. M. Shamim, Dept. of ICT, MBSTU
Static Class/Inner Class
A class can be made static only if it is a nested class.
In Java, it is possible to define a class within another class, such classes are known as nested
classes.
TU
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of the class in which it is
nested.
BS
However, the reverse is not true i.e., the enclosing class does not have access to the members of
the nested class.
A nested class is also a member of its enclosing class.
M
As a member of its enclosing class, a nested class can be declared private, public, protected, or
package private(default).
Nested classes are divided into two categories:
T,
static nested class : Nested classes that are declared static are called static nested classes.
inner class : An inner class is a non-static nested class.
f IC
Nested static class doesn’t need reference of Outer class
A static class cannot access non-static members of the Outer class
Example-1
class JavaExample{
t. o
private static String str = "Book";
//Static class
ep
static class MyNestedClass{
//non-static method
public void disp() {
,D
/* If you make the str variable of outer class
* non-static then you will get compilation error
im
* because: a nested static class cannot access non-
* static members of the outer class.
*/
am
System.out.println(str);
}
}
Sh
public static void main(String args[])
{
/* To create instance of nested class we didn't need the outer
* class instance but for a regular nested class you would need
M.
* to create an instance of outer class first
*/
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
S.
obj.disp();
}
}
S. M. Shamim, Dept. of ICT, MBSTU
Example-2
// Java program to demonstrate accessing a static nested class
// outer class
TU
class OuterClass
{
// static member
BS
static int outer_x = 10;
// instance(non-static) member
M
int outer_y = 20;
// private member
T,
private static int outer_private = 30;
f IC
// static nested class
static class StaticNestedClass
{
void display()
{
t. o
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
ep
// can access display private static member of outer class
System.out.println("outer_private = " + outer_private);
,D
// The following statement will give compilation error
// as static nested class cannot directly access non-static membera
// System.out.println("outer_y = " + outer_y);
im
}
}
am
// Driver class
public class StaticNestedClassDemo
Sh
{
public static void main(String[] args)
{
// accessing a static nested class
M.
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();
S.
}
}
S. M. Shamim, Dept. of ICT, MBSTU
Example-3
// Java program to demonstrate accessing a inner class
// outer class
class OuterClass
TU
{
// static member
static int outer_x = 10;
BS
// instance(non-static) member
int outer_y = 20;
M
// private member
private int outer_private = 30;
T,
// inner class
f IC
class InnerClass
{
void display()
{
// can access static member of outer class
t. o
System.out.println("outer_x = " + outer_x);
// can also access non-static member of outer class
ep
System.out.println("outer_y = " + outer_y);
// can also access a private member of the outer class
,D
System.out.println("outer_private = " + outer_private);
}
im
}
}
am
// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
Sh
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
M.
innerObject.display();
}
S.
}
S. M. Shamim, Dept. of ICT, MBSTU
Example-4
// Java program to demonstrate how to implement static and non-static classes in a
Java program.
class OuterClass {
TU
private static String msg = "GeeksForGeeks";
// Static nested class
BS
public static class NestedStaticClass {
// Only static members of Outer class
M
// is directly accessible in nested
// static class
public void printMessage()
T,
{
f IC
// Try making 'message' a non-static variable, there will be compiler error
System.out.println( "Message from nested static class: "+ msg);
}
} t. o
// Non-static nested class - also called Inner class
public class InnerClass {
ep
// Both static and non-static members of Outer class are accessible Inner class
public void display()
{
,D
System.out.println(
"Message from non-static nested class: "
+ msg);
im
}
}
}
am
class Main {
// How to create instance of static and non static nested class?
public static void main(String args[])
{
Sh
// Create instance of nested Static class
OuterClass.NestedStaticClass printer = new OuterClass.NestedStaticClass();
M.
// Call non static method of nested static class
printer.printMessage();
// In order to create instance of Inner class we need an Outer class
S.
// instance. Let us create Outer class instance for creating non-static nested class
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
S. M. Shamim, Dept. of ICT, MBSTU
// Calling non-static method of Inner class
inner.display();
// We can also combine above steps in one
TU
// step to create instance of Inner class
OuterClass.InnerClass innerObject
= new OuterClass().new InnerClass();
BS
// Similarly we can now call Inner class method
innerObject.display();
M
}
}
T,
Comparison between normal or regular class and static nested class
S.NO NORMAL/REGULAR INNER CLASS STATIC NESTED CLASS
f IC
Without an outer class object existing,
Without an outer class object existing,
there may be a static nested class
t. o
there cannot be an inner class object. That
1. object. That is, static nested class object
is, the inner class object is always
ep
is not associated with the outer class
associated with the outer class object.
object.
,D
Inside normal/regular inner class, static Inside static nested class, static
2.
im
members can’t be declared. members can be declared.
am
As main() method can’t be declared, As main() method can be declared, the
3. regular inner class can’t be invoked directly static nested class can be invoked
Sh
from the command prompt. directly from the command prompt.
M.
Both static and non static members of Only a static member of outer class can
4.
outer class can be accessed directly. be accessed directly.
S.