Java Static Keyword

Java Static Keyword

Add Your Heading Text Here

Java Static Keyword:

In Java, the static keyword is used to define class-level variables and methods that can be accessed without creating an instance of the class. Here are some key characteristics of the static keyword in Java:

  • Static variables: When you declare a variable as static, it becomes a class-level variable, which means that all instances of the class share the same variable. You can access a static variable using the class name, rather than an instance of the class.
				
					public class Example {
    static int count = 0;
}

				
			

In this example, we define a class-level variable called count. We can access this variable using the class name:

				
					int x = Example.count;
				
			
  • Static methods: When you declare a method as static, it becomes a class-level method, which means that you can call it using the class name, rather than an instance of the class. Static methods cannot access non-static instance variables or methods.
				
					public class Example {
    static void printMessage() {
System.out.println("Hello, world!");
    }		
} 
				
			

In this example, we define a static method called printMessage. We can call this method using the class name:

				
					Example.printMessage();
				
			

 

  • Static blocks: In Java, you can also define static blocks of code, which are executed when the class is loaded into memory. Static blocks are enclosed in braces and are preceded by the static keyword:
				
					public class Example {
    static {
System.out.println("This is a static block.");
    }
} 

				
			

In this example, we define a static block that prints a message to the console when the Example class is loaded into memory.

Here is an example that shows the use of static variables and methods in Java:

				
					public class Example {
   static int count = 0;

   static void incrementCount() {
      count++;
   }

   public static void main(String[] args) {
Example.incrementCount();
Example.incrementCount();
Example.incrementCount();

System.out.println("Count is: " + Example.count);
   }
}

				
			

In this example, we define a class-level variable called count and a static method called incrementCount that increments the count variable. We call the incrementCount method three times and then print the value of count to the console. The output of this program would be:

				
					Count is: 3
				
			
Join To Get Our Newsletter
Spread the love