SlideShare a Scribd company logo
1 of 23
 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();
 }
 }
 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)

More Related Content

What's hot

This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in JavaJin Castor
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAsivasundari6
 

What's hot (20)

This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
Java exception
Java exception Java exception
Java exception
 
Java loops
Java loopsJava loops
Java loops
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
Java Streams
Java StreamsJava Streams
Java Streams
 

Viewers also liked

Viewers also liked (20)

Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Java(Access Modifiers)
Java(Access Modifiers)Java(Access Modifiers)
Java(Access Modifiers)
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Visibility control in java
Visibility control in javaVisibility control in java
Visibility control in java
 
Java Inner Classes
Java Inner ClassesJava Inner Classes
Java Inner Classes
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Java packages
Java packagesJava packages
Java packages
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 

Similar to 6. static keyword

Similar to 6. static keyword (20)

Static keyword.pptx
Static keyword.pptxStatic keyword.pptx
Static keyword.pptx
 
Static variable
Static  variableStatic  variable
Static variable
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
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
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Chap08
Chap08Chap08
Chap08
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
 
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCECONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
CONSTRUCTORS IN C++ +2 COMPUTER SCIENCE
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Oop
OopOop
Oop
 
Java session5
Java session5Java session5
Java session5
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdf
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 

More from Indu Sharma Bhardwaj (18)

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

Recently uploaded

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

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();  }  }
  • 9.
  • 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)