SlideShare uma empresa 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

Mais conteúdo relacionado

Semelhante a Lecture 6.pptx

Class loader basic
Class loader basicClass loader basic
Class loader basic
명철 강
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 

Semelhante 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

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 

Último (20)

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
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
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...
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 

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