0% found this document useful (0 votes)
17 views5 pages

Java Static Variables and Methods Explained

The document discusses static variables, methods, and blocks in Java. It provides examples of declaring and using static variables to share data among instances. Static methods can access static data and do not require object instantiation. Static blocks initialize static variables when the class loads. The "this" keyword refers to the current object and is used to distinguish class attributes from parameters with the same name.

Uploaded by

Khan.ali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views5 pages

Java Static Variables and Methods Explained

The document discusses static variables, methods, and blocks in Java. It provides examples of declaring and using static variables to share data among instances. Static methods can access static data and do not require object instantiation. Static blocks initialize static variables when the class loads. The "this" keyword refers to the current object and is used to distinguish class attributes from parameters with the same name.

Uploaded by

Khan.ali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Practical 07:- Write a program in java to implement the static variable,

static methods and static block. Also implement the “this” keyword.

Introduction

Java static keyword:


The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs
to the class than an instance of the class.
The static can be:
• Static Variables
• Static Methods
• Static Blocks of Code.
Static keyword in java in Java indicates that a particular member is not an instance, but
rather part of a type. The static member will be shared among all instances of the class,
so we will only create one instance of it.

If any member in a class is declared as static, it means that even before the class is
initiated, all the static members can be accessed and become active. In contrast to this,
non-static members of the same class will cease to exist when there is no object or the
object goes out of scope.

1) Static Variables in Java


When you create an object or instance for a class in Java, each object will have its own
copy of the members such as variables and methods.
Why is the Java main method static?
• It is because the object is not required to call a static method. If it were a non-
static method, JVM creates an object first then call main() method that will lead
the problem of extra memory allocation.

//Java Program to demonstrate the use of static variable


class Student{
int rollno; //instance variable
String name;
static String college ="JMI"; //static variable
Student(int r, String n){ //constructor
rollno = r;
name = n;
}
void display (){ //method to display the values
[Link](“Details of student: ”+rollno+" , "+name+" , "+college);}
}

public class TestStatic{


public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
[Link]();
[Link]();
}
}
/*Output
Details of student: 111 , Karan , JMI
Details of student: 222 , Aryan , JMI */

2) Java static method

If we apply static keyword with any method, it is known as static method.


• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "JMI";
//static method to change the value of static variable
static void change(){
college = "AMU";
}
Student(int r, String n){
rollno = r;
name = n;
}
void display(){
[Link](rollno+" , "+name+" , "+college);}
}
public class TestStaticMethod{
public static void main(String args[]){
[Link](); //calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonu");
//calling display method
[Link]();
[Link]();
[Link]();
}
}
/*Output:
111 , Karan , AMU
222 , Aryan , AMU
333 , Sonu , AMU */
Limitation for the static method:-
There are two main restrictions for the static method. They are:
• The static method can not use non static data member or call non-static method
directly.
• This and super cannot be used in static context.
3) Java static block
• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.

//Java program to demonstrate Static block.


class A2{
static{
[Link](“Static block is invoked”); //inside static block
}
public static void main(String args[]){
[Link](“Hello main”); //inside main method
}
}
/*Output
Static block is invoked
Hello main
*/
“this” Keyword in Java
The this keyword refers to the current object in a method or constructor. The most
common use of the this keyword is to eliminate the confusion between class attributes
and parameters with the same name (because a class attribute is shadowed by a method
or constructor parameter). If you omit the keyword in the example above, the output
would be "0" instead of "5".

this can also be used to:


• Invoke current class constructor
• Invoke current class method
• Return the current class object
• Pass an argument in the method call
• Pass an argument in the constructor call

//Java program to implement this keyword


public class Main {
int x;
public Main(int x) {
this.x = x;
}
public static void main(String[] args) {
Main myObj = new Main(5);
[Link]("Value of x = " + myObj.x);
}
}
/*Output
Value of x = 5
*/

Common questions

Powered by AI

Changing a static variable in Java alters the shared copy of that variable across all instances of the class, meaning that the updated value will be reflected in all existing and future objects of that class. This allows for consistent behavior and uniform data access, as demonstrated by the change in the college variable from 'JMI' to 'AMU,' affecting all Student objects .

The 'this' keyword in Java resolves potential conflicts between class instance variables and formal parameters of constructors by explicitly denoting which variables are part of the object instance. It helps differentiate class attributes from parameters with the same name, preventing shadowing and ensuring that the object's instance variable is correctly assigned .

Static methods in Java have two main limitations: they cannot directly access non-static data members or methods, and they cannot use 'this' or 'super' keywords. This is because static methods belong to the class, not any particular instance, and thus do not have access to instance-specific data or behaviors .

The Java main method is declared as static because it allows the Java Virtual Machine (JVM) to invoke it without creating an instance of the class. If the main method were not static, the JVM would need to create an object first, which could lead to unnecessary memory allocation and complications during the execution process .

A static block in Java is used to initialize static data members and is executed only once at the time of class loading, before the execution of the main method or any other instance methods. This ensures that any static data the class needs is initialized before any other operations can be performed .

When a Java program with both static blocks and a main method is executed, static blocks will run first, initializing the static data before any instance methods or the main method are executed. This guarantees that all static data is prepared before being accessed by the program, ensuring reliable initialization and behavior .

Static variables are associated with the class itself rather than any object instance, so they are shared among all instances of the class. They exist for the duration of the program and are initialized when the class is loaded. In contrast, instance variables are tied to specific instances of a class, each having its own separate copy, and their lifecycle matches that of the object, existing only until the object is in scope or garbage collected .

The 'this' keyword is used in methods to refer to the current object instance, increasing clarity in object-oriented programming. It allows methods to access instance variables and call other methods within the same object accurately. This is particularly valuable during parameter passing where the parameter name might shadow an instance variable with the same name, ensuring the intended variables are accessed or modified .

Static methods are preferable when functionality does not depend on instance variables and is applicable to all instances of a class. They can be used for utility or helper methods that perform a task without the need for an object's state, ensuring more efficient code since there's no need to instantiate an object just to use the functionality .

The static keyword in Java is primarily used for memory management. It allows class-level variables and methods to be shared across all instances of the class, making them accessible without creating an instance of the class. This is useful for methods like the main method and allows for efficient use of resources as only one copy of the static variables is maintained regardless of the number of objects created from the class .

You might also like