SlideShare une entreprise Scribd logo
1  sur  12
Static
Compiled By:
Vinod Kumar(Asst. Prof.)
Java static keyword
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.
• Java supports definition of global methods and variables that can be
accessed without creating objects of a class. Such members are called Static
members.
• Define a variable by marking with the static methods.
• This feature is useful when we want to create a variable common to all
instances of a class.
• Note: Java creates only one copy for a static variable which can be used
even if the class is never instantiated.
The static can be:
• variable (also known as class variable)
• method (also known as class method)
• block
• nested class
3
Java static variable
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.
Advantage of static variable
• It makes your program memory efficient (i.e. it saves memory).
class Student{
int rollno;
String name;
String university=“CURAJ";
}
Suppose there are 2000 students in our university, 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, university refers to the common
property of all objects . If we make it static , this field will get memory only once.
Example 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+" "+college);
}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Program of counter without static variable and by
static variable
without static variable
class Counter{
int count=0;/*will get memory when instance is c
reated */
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
By static variable
class Counter2{
static int count=0;/*will get memory only once an
d 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();
}
}
6
Static Methods
• A static method belongs to the class rather than object of
a class.
• A class can have methods that are defined as static (e.g.,
main method).
• Static methods can be accessed without using objects.
Also, there is NO need to create objects.
• static method can access static data member and can
change the value of it.
• They are prefixed with keyword “static”
• Static methods are generally used to group related library
functions that don’t depend on data members of its class.
For example, Math library functions.
Example :1
class Student9{
int rollno;
String name;
static String university = "ITS";
static void change(){
university = “Curaj";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+university);
}
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();
}
}
Output:-
111 Karan Curaj
222 Aryan Curaj
333 Sonoo Curaj
Example: 2
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);
}
}
Output :
125
Comparator class with Static methods
/* Comparator.java: A class with static data
items comparison methods*/
class Comparator {
public static int max(int a, int b)
{
if( a > b)
return a;
else
return b;
}
public static String max(String a, String b)
{
if( a.compareTo (b) > 0)
return a;
else
return b;
}
}
class MyClass {
public static void main(String args[])
{
String s1 = "Melbourne";
String s2 = "Sydney";
String s3 = "Adelaide";
int a = 10;
int b = 20;
System.out.println(Comparator.max(a, b));
// which number is big
System.out.println(Comparator.max(s1, s2));
// which city is big
System.out.println(Comparator.max(s1, s3));
// which city is big
}
}
9
Directly accessed using
ClassName (NO Objects)
10
Static methods restrictions
• They can only call other static methods.
• They can only access static data.
• They cannot refer to “this” or “super” (more later) in anyway.
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main
Can we execute a program without
main() method?
• 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);
}
}

Contenu connexe

Tendances

Type casting in java
Type casting in javaType casting in java
Type casting in javaFarooq Baloch
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 

Tendances (20)

Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
OOP java
OOP javaOOP java
OOP java
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 

En vedette

Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23myrajendra
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Appletbackdoor
 
Selenium ide material (2)
Selenium ide material (2)Selenium ide material (2)
Selenium ide material (2)Sriram Angajala
 
Basics of applets.53
Basics of applets.53Basics of applets.53
Basics of applets.53myrajendra
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keywordtanu_jaswal
 
L5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classL5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classteach4uin
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programmingmcanotes
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in javaHitesh Kumar
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in javaHitesh Kumar
 

En vedette (20)

Java keywords
Java keywordsJava keywords
Java keywords
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
Super keyword.23
Super keyword.23Super keyword.23
Super keyword.23
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
 
Client Side Programming with Applet
Client Side Programming with AppletClient Side Programming with Applet
Client Side Programming with Applet
 
Selenium ide material (2)
Selenium ide material (2)Selenium ide material (2)
Selenium ide material (2)
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Satish training ppt
Satish training pptSatish training ppt
Satish training ppt
 
Basics of applets.53
Basics of applets.53Basics of applets.53
Basics of applets.53
 
Srgoc java
Srgoc javaSrgoc java
Srgoc java
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
L5 classes, objects, nested and inner class
L5 classes, objects, nested and inner classL5 classes, objects, nested and inner class
L5 classes, objects, nested and inner class
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Fundamentals
FundamentalsFundamentals
Fundamentals
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 
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
 
[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP[OOP - Lec 01] Introduction to OOP
[OOP - Lec 01] Introduction to OOP
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 

Similaire à Static keyword ppt

Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedPawanMM
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptxVishwanathanS5
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continuedRatnaJava
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued Hitesh-Java
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)Durga Devi
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 

Similaire à Static keyword ppt (20)

Static keyword.pptx
Static keyword.pptxStatic keyword.pptx
Static keyword.pptx
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Static variable
Static  variableStatic  variable
Static variable
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Java session5
Java session5Java session5
Java session5
 
final year project center in Coimbatore
final year project center in Coimbatorefinal year project center in Coimbatore
final year project center in Coimbatore
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptx
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
 
constructer.pptx
constructer.pptxconstructer.pptx
constructer.pptx
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Oop
OopOop
Oop
 
Unit vi(dsc++)
Unit vi(dsc++)Unit vi(dsc++)
Unit vi(dsc++)
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 

Dernier

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 

Dernier (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

Static keyword ppt

  • 2. Java static keyword 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. • Java supports definition of global methods and variables that can be accessed without creating objects of a class. Such members are called Static members. • Define a variable by marking with the static methods. • This feature is useful when we want to create a variable common to all instances of a class. • Note: Java creates only one copy for a static variable which can be used even if the class is never instantiated. The static can be: • variable (also known as class variable) • method (also known as class method) • block • nested class
  • 3. 3 Java static variable 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. Advantage of static variable • It makes your program memory efficient (i.e. it saves memory). class Student{ int rollno; String name; String university=“CURAJ"; } Suppose there are 2000 students in our university, 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, university refers to the common property of all objects . If we make it static , this field will get memory only once.
  • 4. Example 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+" "+college); } public static void main(String args[]){ Student8 s1 = new Student8(111,"Karan"); Student8 s2 = new Student8(222,"Aryan"); s1.display(); s2.display(); } }
  • 5. Program of counter without static variable and by static variable without static variable class Counter{ int count=0;/*will get memory when instance is c reated */ Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } By static variable class Counter2{ static int count=0;/*will get memory only once an d 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(); } }
  • 6. 6 Static Methods • A static method belongs to the class rather than object of a class. • A class can have methods that are defined as static (e.g., main method). • Static methods can be accessed without using objects. Also, there is NO need to create objects. • static method can access static data member and can change the value of it. • They are prefixed with keyword “static” • Static methods are generally used to group related library functions that don’t depend on data members of its class. For example, Math library functions.
  • 7. Example :1 class Student9{ int rollno; String name; static String university = "ITS"; static void change(){ university = “Curaj"; } Student9(int r, String n){ rollno = r; name = n; } void display () { System.out.println(rollno+" "+name+" "+university); } 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(); } } Output:- 111 Karan Curaj 222 Aryan Curaj 333 Sonoo Curaj
  • 8. Example: 2 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); } } Output : 125
  • 9. Comparator class with Static methods /* Comparator.java: A class with static data items comparison methods*/ class Comparator { public static int max(int a, int b) { if( a > b) return a; else return b; } public static String max(String a, String b) { if( a.compareTo (b) > 0) return a; else return b; } } class MyClass { public static void main(String args[]) { String s1 = "Melbourne"; String s2 = "Sydney"; String s3 = "Adelaide"; int a = 10; int b = 20; System.out.println(Comparator.max(a, b)); // which number is big System.out.println(Comparator.max(s1, s2)); // which city is big System.out.println(Comparator.max(s1, s3)); // which city is big } } 9 Directly accessed using ClassName (NO Objects)
  • 10. 10 Static methods restrictions • They can only call other static methods. • They can only access static data. • They cannot refer to “this” or “super” (more later) in anyway. class A2{ static{System.out.println("static block is invoked");} public static void main(String args[]){ System.out.println("Hello main"); } } Output: static block is invoked Hello main
  • 11. Can we execute a program without main() method?
  • 12. • 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); } }