SlideShare a Scribd company logo
 Static variable
 Program of counter without static variable
 Program of counter with static variable
 Static method
 Restrictions for static method
 Why main method is static ?
 Static block
 Can we execute a program without main
method ?
 The static keyword in java is used for memory
management mainly. We can apply java static
keyword with variables, methods, blocks and
nested class. The static keyword belongs to
the class than instance of the class.
 The static can be:
◦ variable (also known as class variable)
◦ method (also known as class method)
◦ block
◦ nested class
 If you declare any variable as static, it is
known static variable.
◦ The static variable can be used to refer the common
property of all objects (that is not unique for each
object) e.g. company name of employees,college
name of students etc.
◦ 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).
 class Student{
 int rollno;
 String name;
 String college="ITS";
 }
 Suppose there are 500 students in my college,
now all instance data members will get memory
each time when object is created.All student have
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 get memory only once.
 Java static property is shared to all objects.
 //Program of static variable

 class Student8{
 int rollno;
 String name;
 static String college ="ITS";

 Student8(int r,String n){
 rollno = r;
 name = n;
 }
 void display (){System.out.println(rollno+" "+name+" "+co
llege);}


 public static void main(String args[]){
 Student8 s1 = new Student8(111,"Karan");
 Student8 s2 = new Student8(222,"Aryan");

 s1.display();
 s2.display();
 }
 }
6. static keyword
 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 objects will have the
value 1 in the count variable.
 class Counter{
 int count=0;//will get memory when instance is created

 Counter(){
 count++;
 System.out.println(count);
 }

 public static void main(String args[]){

 Counter c1=new Counter();
 Counter c2=new Counter();
 Counter c3=new Counter();

 }
 }
 As we have mentioned above, static variable
will get the memory only once, if any object
changes the value of the static variable, it will
retain its value.
 class Counter2{
 static int count=0;//will get memory only once and retain its value

 Counter2(){
 count++;
 System.out.println(count);
 }

 public static void main(String args[]){

 Counter2 c1=new Counter2();
 Counter2 c2=new Counter2();
 Counter2 c3=new Counter2();

 }
 }
 If you apply static keyword with any method,
it is known as static method.
◦ A static method belongs to the class rather than
object of a class.
◦ A static method can be invoked without the need
for creating an instance of a class.
◦ static method can access static data member and
can change the value of it.
 //Program of changing the common property of all objects(static field).

 class Student9{
 int rollno;
 String name;
 static String college = "ITS";

 static void change(){
 college = "BBDIT";
 }

 Student9(int r, String n){
 rollno = r;
 name = n;
 }


 void display (){System.out.println(rollno+" "+name+" "+college);}

 public static void main(String args[]){
 Student9.change();

 Student9 s1 = new Student9 (111,"Karan");
 Student9 s2 = new Student9 (222,"Aryan");
 Student9 s3 = new Student9 (333,"Sonoo");

 s1.display();
 s2.display();
 s3.display();
 }
 }
 //Program to get cube of a given number by static m
ethod

 class Calculate{
 static int cube(int x){
 return x*x*x;
 }

 public static void main(String args[]){
 int result=Calculate.cube(5);
 System.out.println(result);
 }
 }
 There are two main restrictions for the static
method. They are:
◦ 1. The static method can not use non static data
member or call non-static method directly.
◦ 2. this and super cannot be used in static context.
 class A{
 int a=40;//non static

 public static void main(String args[]){
 System.out.println(a);
 }
 }
 Ans) 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.
 Is used to initialize the static data member.
 It is executed before main method at the time
of classloading.
 class A2{
 static{System.out.println("static block is invo
ked");}
 public static void main(String args[]){
 System.out.println("Hello main");
 }
 }
 Output:static block is invoked
 Hello main
 Ans) Yes, one of the way is static block but in
previous version of JDK not in JDK 1.7.
 class A3{
 static{
 System.out.println("static block is invoked");
 System.exit(0);
 }
 }
 Output:static block is invoked (if not JDK7)
 In JDK7 and above, output will be:
 Output:Error: Main method not found in class
A3, please define the main method as: public
static void main(String[] args)
Ad

More Related Content

What's hot (20)

Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
Lovely Professional University
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
Muhammad Hammad Waseem
 
Packages in java
Packages in javaPackages in java
Packages in java
Kavitha713564
 
What is Constructors and Destructors in C++ (Explained with Example along wi...
What is Constructors and Destructors in  C++ (Explained with Example along wi...What is Constructors and Destructors in  C++ (Explained with Example along wi...
What is Constructors and Destructors in C++ (Explained with Example along wi...
Pallavi Seth
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
Haldia Institute of Technology
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
Muthukumaran Subramanian
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Madishetty Prathibha
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 

Viewers also liked (20)

Java static keyword
Java static keywordJava static keyword
Java static keyword
Ahmed Shawky El-faky
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
Srinivas Reddy
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Java(Access Modifiers)
Java(Access Modifiers)Java(Access Modifiers)
Java(Access Modifiers)
Shridhar Ramesh
 
Java keywords
Java keywordsJava keywords
Java keywords
Ravi_Kant_Sahu
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
Sourabrata Mukherjee
 
Visibility control in java
Visibility control in javaVisibility control in java
Visibility control in java
Tech_MX
 
Java Inner Classes
Java Inner ClassesJava Inner Classes
Java Inner Classes
Jussi Pohjolainen
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
Muthukumaran Subramanian
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
Ravi_Kant_Sahu
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
kamal kotecha
 
Packages in java
Packages in javaPackages in java
Packages in java
Abhishek Khune
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
Information Technology
 
Java packages
Java packagesJava packages
Java packages
BHUVIJAYAVELU
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
vanithaRamasamy
 
Ad

Similar to 6. static keyword (20)

Static keyword.pptx
Static keyword.pptxStatic keyword.pptx
Static keyword.pptx
KishanMishra44
 
Lecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptxLecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptx
IkaDeviPerwitasari1
 
Static variable
Static  variableStatic  variable
Static variable
vishal choudhary
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
AshutoshTrivedi30
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
Infoviaan Technologies
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
Durga Devi
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Java ppt Gandhi Ravi ([email protected])
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Week 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptxWeek 3-LectureA Object Oriented Programmings.pptx
Week 3-LectureA Object Oriented Programmings.pptx
FarhanGhafoor7
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
cbeproject centercoimbatore
 
Chap08
Chap08Chap08
Chap08
Terry Yoast
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
PawanMM
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
Nagaraju Pamarthi
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
Venugopalavarma Raja
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
Lovely Professional University
 
Oop
OopOop
Oop
dilshod1988
 
Java session5
Java session5Java session5
Java session5
Jigarthacker
 
Ad

More from Indu Sharma Bhardwaj (18)

E model
E modelE model
E model
Indu Sharma Bhardwaj
 
E commerce
E commerceE commerce
E commerce
Indu Sharma Bhardwaj
 
Ui design final
Ui design finalUi design final
Ui design final
Indu Sharma Bhardwaj
 
Testing
TestingTesting
Testing
Indu Sharma Bhardwaj
 
Software re engineering
Software re engineeringSoftware re engineering
Software re engineering
Indu Sharma Bhardwaj
 
Software project management 3
Software project management 3Software project management 3
Software project management 3
Indu Sharma Bhardwaj
 
Software project management
Software project managementSoftware project management
Software project management
Indu Sharma Bhardwaj
 
Software process and project metrics
Software process and project metricsSoftware process and project metrics
Software process and project metrics
Indu Sharma Bhardwaj
 
Software maintenance
Software maintenanceSoftware maintenance
Software maintenance
Indu Sharma Bhardwaj
 
Software resuse
Software  resuseSoftware  resuse
Software resuse
Indu Sharma Bhardwaj
 
Risk analysis
Risk analysisRisk analysis
Risk analysis
Indu Sharma Bhardwaj
 
Design final
Design finalDesign final
Design final
Indu Sharma Bhardwaj
 
Debugging
DebuggingDebugging
Debugging
Indu Sharma Bhardwaj
 
10 common english mistakes
10 common english mistakes10 common english mistakes
10 common english mistakes
Indu Sharma Bhardwaj
 
3. jvm
3. jvm3. jvm
3. jvm
Indu Sharma Bhardwaj
 
4. method overloading
4. method overloading4. method overloading
4. method overloading
Indu Sharma Bhardwaj
 
2. hello java
2. hello java2. hello java
2. hello java
Indu Sharma Bhardwaj
 
1 .java basic
1 .java basic1 .java basic
1 .java basic
Indu Sharma Bhardwaj
 

Recently uploaded (20)

Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 

6. static keyword

  • 1.  Static variable  Program of counter without static variable  Program of counter with static variable  Static method  Restrictions for static method  Why main method is static ?  Static block  Can we execute a program without main method ?
  • 2.  The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
  • 3.  The static can be: ◦ variable (also known as class variable) ◦ method (also known as class method) ◦ block ◦ nested class
  • 4.  If you declare any variable as static, it is known static variable. ◦ The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc. ◦ The static variable gets memory only once in class area at the time of class loading.
  • 5.  It makes your program memory efficient (i.e it saves memory).
  • 6.  class Student{  int rollno;  String name;  String college="ITS";  }  Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have 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 get memory only once.  Java static property is shared to all objects.
  • 7.  //Program of static variable   class Student8{  int rollno;  String name;  static String college ="ITS";   Student8(int r,String n){  rollno = r;  name = n;  }  void display (){System.out.println(rollno+" "+name+" "+co llege);} 
  • 8.   public static void main(String args[]){  Student8 s1 = new Student8(111,"Karan");  Student8 s2 = new Student8(222,"Aryan");   s1.display();  s2.display();  }  }
  • 10.  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 objects will have the value 1 in the count variable.
  • 11.  class Counter{  int count=0;//will get memory when instance is created   Counter(){  count++;  System.out.println(count);  }   public static void main(String args[]){   Counter c1=new Counter();  Counter c2=new Counter();  Counter c3=new Counter();   }  }
  • 12.  As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
  • 13.  class Counter2{  static int count=0;//will get memory only once and retain its value   Counter2(){  count++;  System.out.println(count);  }   public static void main(String args[]){   Counter2 c1=new Counter2();  Counter2 c2=new Counter2();  Counter2 c3=new Counter2();   }  }
  • 14.  If you apply static keyword with any method, it is known as static method. ◦ A static method belongs to the class rather than object of a class. ◦ A static method can be invoked without the need for creating an instance of a class. ◦ static method can access static data member and can change the value of it.
  • 15.  //Program of changing the common property of all objects(static field).   class Student9{  int rollno;  String name;  static String college = "ITS";   static void change(){  college = "BBDIT";  }   Student9(int r, String n){  rollno = r;  name = n;  }  
  • 16.  void display (){System.out.println(rollno+" "+name+" "+college);}   public static void main(String args[]){  Student9.change();   Student9 s1 = new Student9 (111,"Karan");  Student9 s2 = new Student9 (222,"Aryan");  Student9 s3 = new Student9 (333,"Sonoo");   s1.display();  s2.display();  s3.display();  }  }
  • 17.  //Program to get cube of a given number by static m ethod   class Calculate{  static int cube(int x){  return x*x*x;  }   public static void main(String args[]){  int result=Calculate.cube(5);  System.out.println(result);  }  }
  • 18.  There are two main restrictions for the static method. They are: ◦ 1. The static method can not use non static data member or call non-static method directly. ◦ 2. this and super cannot be used in static context.  class A{  int a=40;//non static   public static void main(String args[]){  System.out.println(a);  }  }
  • 19.  Ans) 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.
  • 20.  Is used to initialize the static data member.  It is executed before main method at the time of classloading.
  • 21.  class A2{  static{System.out.println("static block is invo ked");}  public static void main(String args[]){  System.out.println("Hello main");  }  }  Output:static block is invoked  Hello main
  • 22.  Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.  class A3{  static{  System.out.println("static block is invoked");  System.exit(0);  }  }  Output:static block is invoked (if not JDK7)
  • 23.  In JDK7 and above, output will be:  Output:Error: Main method not found in class A3, please define the main method as: public static void main(String[] args)