Java Program to Check the Accessibility of an Static Variable By a Static Method
Last Updated :
31 Jan, 2023
The Static Keyword is a non-access modifier in Java mainly used for memory management. This static keyword is mainly applicable for the following:
- Variables
- Methods
- Blocks
- Nested Class
Static Variable is a variable that is declared as static means a single copy of the variable is created and shared among all objects at the class level. Static method is a method belonging to the class rather than the object of a class as well as a static method can be invoked without the need for creating an instance of a class.
Note:
- The static variable gets memory only once in the class
- A static method can access static data members and can change the value of it.
Now here we will be discussing out both the cases with a simple demonstration via clean java programs as follows:
- Case 1: Accessibility of a static method/s by static variable/s
- Case 2: Accessibility of a static variable by static method
Case 1: Accessibility of the static methods by static variables
Declaring the variable as static and after that, we called that variable in a static method so that we get that variable as an output.
Example:
Java
import java.io.*;
public class GFG {
static int i = 10 ;
public static void main(String[] args)
{
System.out.println( "Static Variable = " + i);
}
}
|
Output
Static Variable = 10
Time Complexity: O(1)
Auxiliary Space: O(1)
Case 2: Accessibility of a static variable by static method
Declaring the variable, array, and method as static where the static variable and the static array are accessed by the static method. The static method is called without creating an instance of the class.
Example:
Java
import java.io.*;
class GFG {
static int i = 10 ;
static int j = 20 ;
static int temp[] = { 2 , 6 , 3 , 0 , 1 , 7 };
public static void multiply( int n)
{
for ( int k = 0 ; k < n; k++) {
temp[k] = temp[k] * i;
}
}
public static void print_Array( int n)
{
System.out.print( "\nArray = " );
for ( int m = 0 ; m < n; m++) {
System.out.print(temp[m] + " " );
}
}
public static void main(String[] args)
{
System.out.print( "Static variable : " + i);
int n = temp.length;
multiply(n);
print_Array(n);
}
}
|
Output
Static variable : 10
Array = 20 60 30 0 10 70
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...