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

Understanding the Static Keyword in Java

The static keyword in Java is used for memory management and allows variables and methods to be accessed without creating an instance of the class. Static variables and methods are associated with the class itself rather than with individual objects. A static variable loads only once during class loading and can be accessed from the class name, saving memory compared to non-static variables which load for each object instance. The main method must be declared static so that it can be called by the JVM without needing to create an object.

Uploaded by

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

Understanding the Static Keyword in Java

The static keyword in Java is used for memory management and allows variables and methods to be accessed without creating an instance of the class. Static variables and methods are associated with the class itself rather than with individual objects. A static variable loads only once during class loading and can be accessed from the class name, saving memory compared to non-static variables which load for each object instance. The main method must be declared static so that it can be called by the JVM without needing to create an object.

Uploaded by

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

Static keyword in java

The static keyword is used in java mainly for memory management. It is used with variables, methods,

blocks and nested class. It is a keyword that are used for share the same variable or method of a given

class. This is used for a constant variable or a method that is the same for every instance of a class. The

main method of a class is generally labeled static.

No object needs to be created to use static variable or call static methods, just put the class name before

the static variable or method to use them. Static method can not call non-static method.

In java language static keyword can be used for following

 variable (also known as class variable)

 method (also known as class method)

 block

 nested class

Static variable

If any variable we declared as static is known as static variable.

 Static variable is used for fulfill 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.

Syntax for declare static variable:

public static variableName;

Syntax for declare static method:

public static void methodName()


{
.......
.......
}

Syntax for access static methods and static variable

Syntax

[Link]=10;
[Link]();

Example

public static final double PI=3.1415;


public static void main(String args[])
{
......
......
}

Difference between static and final keyword

static keyword always fixed the memory that means that will be located only once in the program where

as final keyword always fixed the value that means it makes variable values constant.

Note: As for as real time statement there concern every final variable should be declared the static but there

is no compulsion that every static variable declared as final.


Example of static variable.

In the below example College_Name is always same, and it is declared as static.

Static Keyword Example in Java

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;
[Link]="abcd";
[Link](s1.roll_no);
[Link]([Link]);
[Link](Student.College_Name);
Student s2=new Student();
s2.roll_no=200;
[Link]="zyx";
[Link](s2.roll_no);
[Link]([Link]);
[Link](Student.College_Name);
}
}

Example

Output:

100

abcd

ITM
200

zyx

ITM

In the above example College_Name variable is commonly sharable by both S1 and S2 objects.

In the above image static data variable are store in method area and non static variable is store in java

stack. Read more about this in JVM Architecture chapter

Why Main Method Declared Static ?

Because object is not required to call static method if main() is non-static method, then jvm create object

first then call main() method due to that face the problem of extra memory allocation
1. lass Student9{  
2.      int rollno;  
3.      String name;  
4.      static String college = "ITS";  
5.        
6.      static void change(){  
7.      college = "BBDIT";  
8.      }  
9.   
10.      Student9(int r, String n){  
11.      rollno = r;  
12.      name = n;  
13.      }  
14.   
15.      void display (){[Link](rollno+" "+name+" "+college);}  
16.   
17.     public static void main(String args[]){  
18.     [Link]();  
19.   
20.     Student9 s1 = new Student9 (111,"Karan");  
21.     Student9 s2 = new Student9 (222,"Aryan");  
22.     Student9 s3 = new Student9 (333,"Sonoo");  
23.   
24.     [Link]();  
25.     [Link]();  
26.     [Link]();  
27.     }  

28. }  

Common questions

Powered by AI

Within the Java memory model, static data is stored in the method area, which is a part of the JVM that contains per-class structures such as runtime constant pool, field and method data, and code for methods. This means static variables and methods are shared among all instances and are not tied to any particular object. In contrast, non-static data is stored in the Java stack within the individual stack frames related to each method call. This allows non-static data to be specific to the instance of the class, as each object has its own stack space .

An application might benefit from using static blocks for initializing complex static variables or performing complicated configurations that are necessary before class execution but independent of any object's state. Static blocks execute once when the class is loaded, ensuring that such setups occur at class loading rather than object instantiation. This contrasts with static methods, which require explicit invocation and do not execute automatically upon class loading, making them less suitable for necessary pre-run setup tasks .

The primary reason for using static keywords in Java, particularly for memory management, is to ensure that memory is allocated only once for shared data or methods. A static variable or method associated with a class allows common resources, such as a company name or a method, to be shared amongst all instances of that class. This improves memory efficiency by not allocating memory repeatedly for each instance and is achieved by storing such static data in the method area of the JVM instead of on individual stack frames .

The syntax for declaring a static variable in Java is 'public static variableName;' An example scenario where using a static variable is advantageous is when storing a company's name for all employee objects. This ensures that the same company name is used without allocating separate memory for each employee object, thus enhancing memory efficiency .

Declaring a method as static is particularly beneficial when the method is utility-based, such as mathematical operations like 'Math.sqrt()' or 'Math.random()', where the functionality does not depend on the state of an instance but serves general purposes. The benefit is in ease of access and avoiding the need for object instantiation, contributing to memory and performance efficiency. However, the trade-off is that static methods cannot access non-static fields or methods of the class, limiting their applicability when instance-specific behavior is needed .

The static keyword in Java is used to allocate memory only once for variables or methods that need to be shared across all instances of a class, thereby enhancing memory management by reducing redundancy. In contrast, the final keyword makes a variable's value constant, thereby preventing any changes once it is initialized. While both keywords can be used to optimize resource utilization (static through shared memory, and final through immutable values), they serve different purposes: static for shared memory allocation, and final for constant value assurance .

Static variables are allocated memory only once, within the method area of JVM, leading to efficient memory usage as they are shared across all instances. Instance variables are allocated memory within the stack space of each object instance, which means each object has its own copy. This affects application performance because frequent creation and destruction of objects can result in considerable memory overhead. By using static variables for shared resources, applications achieve better memory utilization and potentially faster execution .

Static variables in Java are shared between instances of a class, meaning they maintain a single copy that all instances can access. For example, consider a 'Student' class with a static variable 'College_Name'. Once an 'Student' object sets the value of 'College_Name', all other instances reflect this change. When printing 'College_Name' from different 'Student' objects, it shows the same value across all objects, demonstrating the shared access .

A static method in Java can be invoked using the class name followed by a dot operator and the method name, as in 'ClassName.methodName();'. Static methods cannot access non-static variables or methods directly, and therefore, should only work with static data or other static methods. This restriction ensures that static methods do not depend on any object instance state .

The main method in Java is typically declared as static to allow the JVM to invoke it without needing to create an instance of the class. This design choice avoids the unnecessary overhead of object creation before the program starts executing, thereby saving memory and speeding up the startup process. If the main method were non-static, the JVM would have to instantiate an object first, leading to additional memory allocation and processing time .

You might also like