Smart Programming : Channel
An investment in Knowledge pays the best interest….
Static variables and static
blocks in Java
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
=> static keyword :-
-> static keyword is non-access modifier
-> static keyword can be used with
1. variables
2. block
3. methods
4. nested class or inner class (not outer
class)
-> use of static keyword :-
1. It is used to improve share-ability
2. It is used for memory management
1
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
-> static members belong to the class, not objects
=> static variables :-
-> If we declare any variable as static, it is
known as static variable
-> Static variables gets memory allocated in
method area at the time of class loading
-> Example :
2
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
-> Points to remember :-
1. We cannot create static local variable
because main use of static variable is improve
share-ability but local variables have limited share-
ability thus it voilates the rule of static keyword
2. If we declare any variable in static
method, then it will be treated as local variable only
3. We cannot use instance variable inside
static method but we can use static variable inside
instance method
=> static block :-
-> A block created using static keyword is known
as static block
-> Static block is executed at the time of class
loading
3
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
-> Use of static block :-
1. We can create static block to initialize
static variables
2. We can create static block to load native
libraries at class loading time
-> Syntax :
static
{
-> static blockes will be executed from top to
bottom
4
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
Interview Question :
1. Can we print hello without using main method
Yes but before JDK 7 version
5
Smart Programming (Mohali, Chandigarh India)
Call or Whats App Online & Industrial Training: +91 62838-30308
Company Links & Contacts
Company Name: Smart Programming (+91 62838-30308)
Address : Chandigarh & Mohali (Punjab), India
Websites: https://www.smartprogramming.in/
https://courses.smartprogramming.in
Android App:
https://play.google.com/store/apps/details?id=com.sma
rtprogramming
YouTube Channel:
https://www.youtube.com/c/SmartProgramming