SlideShare una empresa de Scribd logo
1 de 19
Lecture 6- JAVA
Static Members in java
• The class level members which have static keyword in their
definition are called static members.
Types of Static Members: Java supports four types of static members
– Static Variables
– Static Blocks
– Static Methods
• All static members are identified and get memory location at the
time of class loading by default by JVM in Method area.
• Only static variables get memory location, methods will not have
separate memory location like variables.
• Static Methods are just identified and can be accessed directly
without object creation.
Static variable:-
 If any variable we declared as static is known as static variable.
 Static variable is used for fulfil the common requirement.
 For Example company name of employees, college name of students etc.
Name of the college is common for all students.
 The static variable allocate memory only once in class area at the time of
class loading.
Advantage of static variable
• Using static variable we make our program memory efficient (i.e. it saves
memory).
When and why we use static variable
 Suppose we want to store record of all employee of any company, in this
case employee id is unique for every employee but company name is
common for all.
 When we create a static variable as a company name then only once
memory is allocated otherwise it allocate a memory space each time for
every employee.
Example of static variable.
In the below example College_Name is always same, and it is declared as
static.
class Student
{
int roll_no;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.name);
System.out.println(Student.College_
Name);
Student s2=new Student();
s2.roll_no=200;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.name);
System.out.println(Student.College_Na
me);
}
}
© 2006 Pearson Addison-Wesley. All rights
reserved
Static Variables
Any instance variable can be declared static by including the word “static”
immediately before the type specification
What’s Different about a static variable?
1) A static variable can be referenced either using its class name or
an name object.
public class StaticStuff {
public static double staticDouble;
public static String staticString;
. . .
}
StaticStuff s1, s2;
s1 = new StaticStuff();
s2 = new StaticStuff();
s1.staticDouble = 3.7;
System.out.println( s1.staticDouble );
System.out.println( s2.staticDouble );
s1.staticString = “abc”;
s2.staticString = “xyz”;
System.out.println( s1.staticString );
System.out.println( s2.staticString );
2) Instantiating a second object of the same type does not increase
the number of static variables.
Example
Important
• We can not declare local variables as static it leads to compile
time error "illegal start of expression".
• Because being static variable it must get memory at the time
of class loading, which is not possible to provide memory to
local variable at the time of class loading.
• All static variables are executed by JVM in the order of they
defined from top to bottom.
• JVM provides individual memory location to each static
variable in method area only once in a class life time.
Life time and scope:
• Static variable get life as soon as class is loaded into JVM and
is available till class is removed from JVM or JVM is shutdown.
• And its scope is class scope means it is accessible throughout
the class.
Static Methods
In Java it is possible to declare methods to belong to a class rather
than an object. This is done by declaring them to be static.
the declaration
Static methods are
declared by inserting the
word “static” immediately
after the scope specifier
(public, private or
protected).
the call
Static methods are called
using the name of their
class in place of
an object reference.
public class DemoStatic {
public static int sum(int n) {
int total = 0;
for (int k=0; k!=n; k++) {
total = total + k;
}
return total;
}
}
int x=10;
...
Int result = DemoStatic.sum(x);
Static Methods - Why?
Static methods are useful for methods that are disassociated from all objects,
excepting their parameters.
A good example of the utility of static method is found in the
standard Java class, called Math.
public class Math {
public static double abs(double d) {...}
public static int abs(int k) {...}
public static double cos(double d) {...}
public static double pow(double b, double exp) {...}
public static double random() {...}
public static int round(float f) {...}
public static long round(double d) {...}
public static double sin(double d) {...}
public static double sqrt(double d) {...}
public static double tan(double d) {...}
. . .
}
Static Method Restrictions
Since a static method belongs to a class, not an object, there are limitations.
The body of a static method cannot reference any non-static (instance) variable.
Example (the run.java file)
The body of a static method cannot call any non-static method unless it is
applied to some other instantiated object.
The body of a static method can instantiate objects.
However, ...
public class run {
public static void main(String[] args) {
Driver driver = new Driver();
}
}
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
}
}
Directly accessed using
ClassName (NO Objects)
Order of execution of static variables and main
method:
• First all static variables are executed in the order they defined from top to
bottom then main method is executed.
Example Program:
class StaticDemo
{
static int a=m1();
static int m1() {
System.out.println("variable a is created");
return 10;
}
static int b=m2();
static int m2(){
System.out.println("variable b is created");
return 20;
}
public static void main(String [] args){
System.out.println("in main method");
System.out.println("a="+a);
System.out.println("b="+b);
}
}
OUTPUT
10
30
30
30
Static block in Java
• Static block also known as static initializer
• Static blocks are the blocks with static keyword.
• Static blocks wont have any name in its prototype.
• Static blocks are class level.
• Static block will be executed only once.
• No return statements.
• No arguments.
• No this or super keywords supported.
When and where static blocks will be
executed?
• Static blocks will be executed at the time of
class loading by the JVM by creating separate
stack frames in java stacks area.
• Static blocks will be executed in the order they
defined from top to bottom.
Example For Order of execution of
static block and main method:
class StaticBlockDemo
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Main method executed");
}
static{
System.out.println("First static block executed");
}
static{
System.out.println("Second static block executed");
}
static{
System.out.println("Third static block executed");
}
Output:
First static block execute
Second static block exec
Third static block execut
Main method executed
Method Overloading
• Overloading is also a feature of OOP languages
like Java that is related to compile time (or
static) polymorphism.
• If a class have multiple methods by same
name but different parameters, it is known
as Method Overloading.
• If we have to perform only one operation,
having same name of the methods increases
the readability of the program.
Example
class Calculation{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c){
System.out.println(a+b+c);
}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Can we overload static methods?
• The answer is ‘Yes’. We can have two ore more
static methods with same name, but differences
in input parameters.
• For example, consider the following Java
program.
// filename Test.java
public class Test {
public static void foo() {
System.out.println("Test.foo() called ");
}
public static void foo(int a) {
System.out.println("Test.foo(int) called ");
}
public static void main(String args[])
{
Test.foo();
Test.foo(10);
}
Output:
Test.foo() called
Test.foo(int) called

Más contenido relacionado

Similar a Lecture 6.pptx

JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
Class loader basic
Class loader basicClass loader basic
Class loader basic명철 강
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Class method object
Class method objectClass method object
Class method objectMinal Maniar
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalorerajkamaltibacademy
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2Sherihan Anver
 

Similar a Lecture 6.pptx (20)

6. static keyword
6. static keyword6. static keyword
6. static keyword
 
BCA Class and Object (3).pptx
BCA Class and Object (3).pptxBCA Class and Object (3).pptx
BCA Class and Object (3).pptx
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Static Members-Java.pptx
Static Members-Java.pptxStatic Members-Java.pptx
Static Members-Java.pptx
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Java session4
Java session4Java session4
Java session4
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Class method object
Class method objectClass method object
Class method object
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
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 interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 

Último

MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGSIVASHANKAR N
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxfenichawla
 

Último (20)

MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTINGMANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
MANUFACTURING PROCESS-II UNIT-1 THEORY OF METAL CUTTING
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 

Lecture 6.pptx

  • 2. Static Members in java • The class level members which have static keyword in their definition are called static members. Types of Static Members: Java supports four types of static members – Static Variables – Static Blocks – Static Methods • All static members are identified and get memory location at the time of class loading by default by JVM in Method area. • Only static variables get memory location, methods will not have separate memory location like variables. • Static Methods are just identified and can be accessed directly without object creation.
  • 3. Static variable:-  If any variable we declared as static is known as static variable.  Static variable is used for fulfil the common requirement.  For Example company name of employees, college name of students etc. Name of the college is common for all students.  The static variable allocate memory only once in class area at the time of class loading. Advantage of static variable • Using static variable we make our program memory efficient (i.e. it saves memory).
  • 4. When and why we use static variable  Suppose we want to store record of all employee of any company, in this case employee id is unique for every employee but company name is common for all.  When we create a static variable as a company name then only once memory is allocated otherwise it allocate a memory space each time for every employee.
  • 5. Example of static variable. In the below example College_Name is always same, and it is declared as static. class Student { int roll_no; String name; static String College_Name="ITM"; }
  • 6. class StaticDemo { public static void main(String args[]) { Student s1=new Student(); s1.roll_no=100; s1.name="abcd"; System.out.println(s1.roll_no); System.out.println(s1.name); System.out.println(Student.College_ Name); Student s2=new Student(); s2.roll_no=200; s2.name="zyx"; System.out.println(s2.roll_no); System.out.println(s2.name); System.out.println(Student.College_Na me); } }
  • 7. © 2006 Pearson Addison-Wesley. All rights reserved Static Variables Any instance variable can be declared static by including the word “static” immediately before the type specification What’s Different about a static variable? 1) A static variable can be referenced either using its class name or an name object. public class StaticStuff { public static double staticDouble; public static String staticString; . . . } StaticStuff s1, s2; s1 = new StaticStuff(); s2 = new StaticStuff(); s1.staticDouble = 3.7; System.out.println( s1.staticDouble ); System.out.println( s2.staticDouble ); s1.staticString = “abc”; s2.staticString = “xyz”; System.out.println( s1.staticString ); System.out.println( s2.staticString ); 2) Instantiating a second object of the same type does not increase the number of static variables. Example
  • 8. Important • We can not declare local variables as static it leads to compile time error "illegal start of expression". • Because being static variable it must get memory at the time of class loading, which is not possible to provide memory to local variable at the time of class loading. • All static variables are executed by JVM in the order of they defined from top to bottom. • JVM provides individual memory location to each static variable in method area only once in a class life time. Life time and scope: • Static variable get life as soon as class is loaded into JVM and is available till class is removed from JVM or JVM is shutdown. • And its scope is class scope means it is accessible throughout the class.
  • 9. Static Methods In Java it is possible to declare methods to belong to a class rather than an object. This is done by declaring them to be static. the declaration Static methods are declared by inserting the word “static” immediately after the scope specifier (public, private or protected). the call Static methods are called using the name of their class in place of an object reference. public class DemoStatic { public static int sum(int n) { int total = 0; for (int k=0; k!=n; k++) { total = total + k; } return total; } } int x=10; ... Int result = DemoStatic.sum(x);
  • 10. Static Methods - Why? Static methods are useful for methods that are disassociated from all objects, excepting their parameters. A good example of the utility of static method is found in the standard Java class, called Math. public class Math { public static double abs(double d) {...} public static int abs(int k) {...} public static double cos(double d) {...} public static double pow(double b, double exp) {...} public static double random() {...} public static int round(float f) {...} public static long round(double d) {...} public static double sin(double d) {...} public static double sqrt(double d) {...} public static double tan(double d) {...} . . . }
  • 11. Static Method Restrictions Since a static method belongs to a class, not an object, there are limitations. The body of a static method cannot reference any non-static (instance) variable. Example (the run.java file) The body of a static method cannot call any non-static method unless it is applied to some other instantiated object. The body of a static method can instantiate objects. However, ... public class run { public static void main(String[] args) { Driver driver = new Driver(); } }
  • 12. 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 } } Directly accessed using ClassName (NO Objects)
  • 13. Order of execution of static variables and main method: • First all static variables are executed in the order they defined from top to bottom then main method is executed. Example Program: class StaticDemo { static int a=m1(); static int m1() { System.out.println("variable a is created"); return 10; } static int b=m2(); static int m2(){ System.out.println("variable b is created"); return 20; } public static void main(String [] args){ System.out.println("in main method"); System.out.println("a="+a); System.out.println("b="+b); } } OUTPUT 10 30 30 30
  • 14. Static block in Java • Static block also known as static initializer • Static blocks are the blocks with static keyword. • Static blocks wont have any name in its prototype. • Static blocks are class level. • Static block will be executed only once. • No return statements. • No arguments. • No this or super keywords supported.
  • 15. When and where static blocks will be executed? • Static blocks will be executed at the time of class loading by the JVM by creating separate stack frames in java stacks area. • Static blocks will be executed in the order they defined from top to bottom.
  • 16. Example For Order of execution of static block and main method: class StaticBlockDemo { public static void main (String[] args) throws java.lang.Exception { System.out.println("Main method executed"); } static{ System.out.println("First static block executed"); } static{ System.out.println("Second static block executed"); } static{ System.out.println("Third static block executed"); } Output: First static block execute Second static block exec Third static block execut Main method executed
  • 17. Method Overloading • Overloading is also a feature of OOP languages like Java that is related to compile time (or static) polymorphism. • If a class have multiple methods by same name but different parameters, it is known as Method Overloading. • If we have to perform only one operation, having same name of the methods increases the readability of the program.
  • 18. Example class Calculation{ void sum(int a,int b) { System.out.println(a+b); } void sum(int a,int b,int c){ System.out.println(a+b+c); } public static void main(String args[]){ Calculation obj=new Calculation(); obj.sum(10,10,10); obj.sum(20,20); } }
  • 19. Can we overload static methods? • The answer is ‘Yes’. We can have two ore more static methods with same name, but differences in input parameters. • For example, consider the following Java program. // filename Test.java public class Test { public static void foo() { System.out.println("Test.foo() called "); } public static void foo(int a) { System.out.println("Test.foo(int) called "); } public static void main(String args[]) { Test.foo(); Test.foo(10); } Output: Test.foo() called Test.foo(int) called