Title: Important of Static Keyword in Java Programming
1Presentation on Static keyword
Website www.javabykiran.com Contact 8888558802
2Static Keyword in
Website www.javabykiran.com Contact 8888558802
3About Us
- Having experience in teaching Java for more than
8 years on part-time basis. Has more than 12
years of work experience in IT industry. Till now
many projects have been successfully completed
and has given guidance to more than 4000 students.
4Things to Remember
JBK
- Static is a keyword used for memory management
- Static means single copy storage for variable or
method - Static keyword can be applied to variables,
methods, inner class and blocks - Static members belongs to class rather than
instance of class
5Things to Remember
JBK
- Static in java is a keyword that indicates that
the variables or functions are shared between all
the instances of a particular class since it
belongs to the type, not the object. It is used
when the programmer wants to share the same
variable or method of a class.
6Static Variable
JBK
- The variable preceded by static keyword is
static variable - static int a10 //variable
- static void m1()
-
- // method
-
- Static variable is used to refer common
property of all objects of class
7How to access static variable?
JBK
- There are two ways to access static variable
- Static variable can be accessed by Class name
- A. a A is class name
- Where A is the class name and a is a static
variable declared in that class - Static variable can be accessed by object
- I have a class name called Sample. Now, we
can create the object of the Sample class - Sample hnew Sample ()
- System.out.println(h.a) //a is static
variable inside sample class
8JBK
How can I access static variable in two ways?
package com.javabykiran.Static / _at_author Java By Kiran / public class Staticvar static int i10 public static void main(String args) Staticvar s new Staticvar() System.out.println(s.i) //Not Recommended System.out.println(Staticvar.i) //Recommended
Output
10 10
9JBK
In the above program, we printed the value of
variable by using object name and by using class
name Static variable gets loaded into the
memory at the time of class loading So, we can
access static variable by reference variables as
well. In the above program, if we create only
the reference of class like Staticvar s1null
System.out.println(s1.i) // possible System.out
.println(Staticvar.i) //possible The above
example compiles and executes successfully
because the static variable get loaded into the
memory at the time of class loading Static
variable and method doesn't belong to
Object/Instance of the class since static
variables are shared across all the instances of
Object.
10Thank You.
JBK