Static Variable:
Static is predefined k/w in java
It can be used to declare Static
variable
Declare static var:
static
String address;
·
If we write the `static` keyword before the
variable name, it becomes a static variable.
·
If we do not write the `static` keyword before
the variable name, it becomes a non-static variable (also known as an instance
variable).
·
Static variable will be created only copy in
memory
·
Static variable will be created in static area
/class area but not in heap area.
·
Static variables are allocated memory only once
during the class loading process in the static area of memory. This memory is
shared across all instances of the class.
Static variables are useful when
you want to have a common property that is shared among all instances of a
class. (or)
whenever there is common value ,
which has to be shared across multiple object- then we can go for static variable.
Access the static variable:
·
Static Variable: Can be accessed in 3 ways
1. Using
Object Reference Variable
2. Using
Class Name
3. Directly
in Static Methods
1. Using Object Reference Variable:
- A static variable can be
accessed using an object reference.
- In the example, the tref object is used to set and
access the college static variable.
- ex:
objRef.StaticMethod();
- However, this approach is
generally not recommended because it implies that the variable is
associated with the instance rather than the class itself.
·
Using Class Name:
className.Static Method();
- The preferred way to access
static variables is using the class name. It clearly indicates that the
variable belongs to the class and is not tied to any specific instance.
- In the example, TestStaticVar.college is used to set and access
the static variable.
·
Directly in Static Methods:
- Inside a static method,
static variables can be accessed directly without any object reference or
class name. This is because static methods and variables are part of the
class itself.
- In the example, the static
variable college is accessed directly in the
main method.
package OOPSBasics;
public class TestStaticVariable {
//
Declare Instance variable (or) non static variable sid of type int , sname of
type String
int
sid; // non static or Instance var
// non static variable or Instance variable (If
we dont use static k/w before data type -)
String
sname; // non static
//
Declare 'static' variable college, Address
of type String
static
String college;
// if
we declare variable with static k/w -
static var
static
String address;
public
static void main(String[] args) // static method
{
//
Static variable can be accessed in 3 ways
// 1. using Obj Reference variable (or) Obj name
//
create obj for class -TestStaticVar
TestStaticVariable
tref = new TestStaticVar();
//
store College = "Jntu";address = "BNG";
tref.college
= "Jntu";
System.out.println("Static
variable can be accessed by using Object Reference variable =" +
tref.college );
// 2. by using Classname
// ex: ClassName.StaticVar
//
store College = "Osmania";
TestStaticVar.college
= "Osmania";
System.out.println("Static
variable can be accessed by using class name =" +TestStaticVar.college );
//
3 .directly use static variable inside static method - main () - static method-
// ex: staticvarName = some value;
//College
= "SV university";
college = "Sv university";
System.out.println("Static
variable can be accessed by static variable directly=" + college);
}
}
o/p:
Static variable can be accessed
by using Object Reference variable =Jntu
Static variable can be accessed
by using class name =Osmania
Static variable can be accessed
by static variable directly=Sv university
Ex: Static variable can be shared to all Objects:
Single
Copy: There is only one copy of a static variable, regardless
of how many objects of the class are created.
Shared
Among Instances: All instances of the class share the same
static variable. If one instance changes the static variable, the change is
reflected across all instances.
Why Use Static Variables?
- Memory Efficiency: Only
one copy exists, saving memory.
- Consistency: Ensures a
value is consistent across all instances of the class.
package OOPSBasics;
public class Student6
{
//
Declare name, sid variables
String
name; // Instance variable or non static
int
sid;
//
Declare 'static' variable -college
static
String college ; // static var
public
static void main(String[] args) {
//create
obj for Student6 class with ref variable s1
Student6 s1 = new Student6();
//
store College = "Jntu";
s1.college
= "Jntu";
//
display static variable college
System.out.println("s1
college=" + s1.college);
//
s1 college=Jntu
//create
obj for Student class with ref variable s2
Student6
s2 =
new Student6();
//
College = "Osmania";
s2.college
="Osmania";
System.out.println("s1
college="+ s1.college);
System.out.println("s2
college="+s2.college);
// s1 college=
//
s2 college=
//create
obj for Student class with ref variable s3
Student6 s3 = new Student6();
//
College = "SV Univerity";
s3.college
="SV university";
System.out.println("s1
college="+ s1.college);
System.out.println("s2
college="+ s2.college);
System.out.println("s3
college="+s3.college);
// s1 college=
// s2
college=
// s3
college=
}
}
o/p:
s1 college=Jntu
s1 college=Osmania
s2 college=Osmania
s1 college=SV university
s2 college=SV university
s3 college=SV university
FAQ What is static variable ?
FAQ when to use static variable ?
Note:
Static variables - we can define
inside the class and out side of method
but not inside method
package OOPSBasics;
public class Student6
{
//
Declare name, sid variables
String
name; // Instance variable or non static
int
sid;
//
Declare 'static' variable -college
static
String college ; // static var
public
static void main(String[] args)
{
//String
address;// local var
// static String
address;//CE: Illegal modifier for parameter address; only final is permitted
//// We cannot declare static variable inside
method
}
}
Static Method:
·
If you write the static
keyword before the method name, it becomes a static method.
·
Ex:
static void staticMethod()
{
System.out.println("This
is a static method.");
}
·
If you do not write the static keyword before the method name, it is a
non-static (instance) method.
·
Ex:
·
void instanceMethod()
·
{
·
System.out.println("This
is an instance method.");
·
}
·
Can
access static variables and static methods.
·
Cannot access instance variables or instance
methods directly.
·
Calling Static Methods in Java:
1.
Calling a Static Method Using an Object
Reference
Ex: objRef.SM1();
2.
Calling a Static Method Using the Class Name
Ex:
className.SM1();
3.
Calling a Static Method from Another Static
Method if they are in the same class.
SM1();
package OOPSBasics;
public class StaticMethodBasics
{
//
define static method M1()
public
static void M1()// M1 - Static Method
{
System.out.println("Calling
Static method");
}
public
static void main(String[] args) //
Static method
{
//
static var/ methods can be accessed in 3
ways
// 1. through object refer
// 2. through class name
// 3. directly access
static variable / static method inside the static method
// 1. create obj for
class- StaticMethodBasics
StaticMethodBasics
s1 = new StaticMethodBasics();
//
call M1()
s1.M1();
//2 className.MethodName();
//
call M1()
StaticMethodBasics.M1();
//
3. // 3.
directly access static variable / static method
//
call M1()
M1();
}
}
o/p:
Calling Static method
Calling Static method
Calling Static method
HW : Define Static variables i.e address, and call static variables by
using 3 ways ?
HW : Define Static method M2() and call static methods by using 3 ways
?
Static Block in Java:
A static block is a group of
statements enclosed in curly braces and preceded by the static keyword
(Or)
A static block is a collection of
statements enclosed in curly braces and preceded by the static keyword
Ex:
static
{
stmts-1;
stmt-2;
}
Behavior of Static Block
- Execution Order: Static
blocks have the highest priority and are executed before the
mainmethod. When the Java Virtual Machine (JVM) loads the class, it checks for any static blocks. - Initialization: If a
static block is present, the JVM executes the static block first, before
executing the
mainmethod. - One-Time Execution: Static
blocks are executed only once, when the class is loaded
·
After the static block completes, the main method is executed,
package OOPSBasics;
public class StaticBlockBasics
{
//
Static block --has the priority before main()
// before executing main ()- First JVM checks that in the current class it has
static block.
//
if static block is there, it executes 1st static block, after completion of all
stmts in side static block
// then it executes main() stmts
// 1st priority for static block only before
main()
//
define static block
static // static block
{
System.out.println("This
is static block");
System.out.println("This
is static block. stmt-2");
}
public
static void main(String[] args)
{
System.out.println("in
Main ()");
}
}
o/p:
This is static block
This is static block. stmt-2
in Main ()
Example with Multiple Static Blocks:
ex3: can we have multiple static
blocks ?
You can have multiple static
blocks in a class, and they are executed in the order they appear in the class
definition.
After executing static block-1
and static block-2 statements, then it executes main().
i.e they will execute
sequentially in the order they are defined.
package Basics;
public class staticBlockBasics {
static // 1st
piority
{
System.out.println("static
block-1 stmt-1");
System.out.println("static
block-1 stmt-2");
}
static
{
System.out.println("static
block-2 stmt-1");
}
public
static void main(String[] args) { // 2nd priority
System.out.println("in
main -method");
}
}
o/p:
------
static block-1 stmt-1
static block-1 stmt-2
static block-2 stmt-1
in main -method
Non static Method (or) Instance Methods:
in class,we can write 'static
methods' and 'non static methods'
package OOPSBasics;
public class Student7
{
//
Define static methods M1()
public
static void M1() // Static method
{
System.out.println("calling
static method");
}
//Define non static Method (or) Instance method M2()
public void M2()// non static Method (or) Instance
Method
{
System.out.println("calling
Non static method (or) Instance method");
}
public
static void main(String[] args)
{
// 2nd priority
System.out.println("in
main -method");
// 3 ways to access static variable and static
method
// 1. obj ref , 2 . classname 3 . directly use
static variable and method inside static
method
// to
access non static variable and non
static method or Instance Methods
// 1.with
help of obj ref variable only, we can access non static variable and non static
method
//
create obj for student class-Student7
//
call M2() directly
Student7 s7 = new Student7();
//
call non static method i.e M2() using
obj ref
s7.M2();
// M2(); //
CE: Cannot make a static reference to the non-static method M2()
//from
the type staticBlockBasics2
// note: if we call nonstatic method from static
method - main directly- we will get Compile time errror
// always
accesss non static variable and non static methods by creating obj for
class and use obj ref var.
}
}
o/p:
in main -method
calling Non static method (or)
Instance method
No comments:
Post a Comment