SlideShare uma empresa Scribd logo
1 de 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)

Mais conteúdo relacionado

Mais procurados

String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
myrajendra
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 

Mais procurados (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
 

Destaque

Visibility control in java
Visibility control in javaVisibility control in java
Visibility control in java
Tech_MX
 
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
 

Destaque (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
 

Semelhante a 6. static keyword

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
KUNALHARCHANDANI1
 

Semelhante a 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
 

Mais de 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
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
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
Safe Software
 

Último (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
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
 
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...
 
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
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

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)