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

Lecture 6.pptx

  • 1.
  • 2.
    Static Members injava • 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:-  Ifany 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 whywe 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 staticvariable. 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 staticvoid 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 PearsonAddison-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 cannot 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 Javait 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 Sincea 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 withStatic 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 executionof 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 inJava • 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 wherestatic 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 Orderof 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 • Overloadingis 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(inta,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 overloadstatic 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