0% found this document useful (0 votes)
27 views

09 Static Keyword in Java

Uploaded by

chintuunagar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

09 Static Keyword in Java

Uploaded by

chintuunagar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

QUE: Explain Static Keyword in Java with proper

examples.
ANS:
➢ The static keyword in Java is mainly used for memory management.

➢ It is used to share the same variable or method of a given class.

➢ The users can apply static keywords with variables, methods, blocks, and
nested classes.

➢ When a member is declared as static, it means that it belongs to the class itself
rather than to instances (objects) of the class.

❖ CHARACTERISTICS OF STATIC KEYWORDS:


Here are some characteristics of the static keyword in Java:
 Shared memory allocation:

➢ Static variables and methods are allocated memory space only


once during the execution of the program.

➢ This memory space is shared among all instances of the class,


which makes static members useful for maintaining global state
or shared functionality.

 Accessible without object instantiation:

➢ Static members can be accessed without the need to create an


instance of the class.

➢ This makes them useful for providing utility functions and


constants that can be used across the entire program.

 Associated with class, not objects:

➢ Static members are associated with the class, not with individual
objects.
➢ This means that changes to a static member are reflected in all
instances of the class, and that you can access static members
using the class name rather than an object reference.
 Cannot access non-static members:

➢ Static methods and variables cannot access non-static members


of a class, as they are not associated with any particular instance
of the class.

 Can be overloaded, but not overridden:

➢ Static methods can be overloaded, which means that you can


define multiple methods with the same name but different
parameters.

➢ However, they cannot be overridden, as they are associated with


the class rather than with a particular instance of the class.

❖ ADVANTAGES:
 Memory efficiency: Static members are allocated memory only once
during the execution of the program, which can result in significant
memory savings for large programs.

 Improved performance: Because static members are associated with


the class rather than with individual instances, they can be accessed more
quickly and efficiently than non-static members.

 Global accessibility: Static members can be accessed from anywhere in


the program, regardless of whether an instance of the class has been
created.

 Encapsulation of utility methods: Static methods can be used to


encapsulate utility functions that don’t require any state information from
an object. This can improve code organization and make it easier to reuse
utility functions across multiple classes.

 Constants: Static final variables can be used to define constants that are
shared across the entire program.

 Class-level functionality: Static methods can be used to define class-


level functionality that doesn’t require any state information from an
object, such as factory methods or helper functions.
❖ THE STATIC KEYWORD IS APPLICABLE FOR THE FOLLOWING
IN JAVA:
1. Blocks
2. Variables
3. Methods
4. Classes
Lets examine all the use of static keyword one by one.

(1) STATIC BLOCKS:

➢ Static blocks are used to initialize static variables.

➢ They are executed only once when the class is loaded into memory,
before the execution of the main method or creation of any object of
that class.

➢ Static blocks are often used for one-time initialization tasks.


public class Example
{
// Static variable
static int number;

// Static block
static
{
System.out.println("Static block is initialized.");

// Initialize the static variable


number = 10;
}
public static void main(String[] args)
{
System.out.println("Number: " + Example.number); // Output: 10
}
}
(2) STATIC VARIABLES

➢ When a variable is declared as static, then a single copy of the variable is


created and shared among all objects at the class level.

➢ Static variables are, essentially, global variables. All instances of the class
share the same static variable.
Important points for static variables:
• We can create static variables at the class level only.
• static block and static variables are executed in the order they are
present in a program.

Example:
class MyClass
{
// Static variable
static int count = 0;

MyClass()
{
count++; // Increment count each time a new object is created
}

public static void main(String[] args)


{
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass obj3 = new MyClass();

// Accessing static variable using class name


System.out.println("Total objects created: " + MyClass.count);
// Output: 3
}
}
(3) STATIC METHODS

➢ When a method is declared with the static keyword, it is known as the


static method.

➢ The most common example of a static method is the main( ) method.

➢ As discussed above, Any static member can be accessed before any


objects of its class are created, and without reference to any object.

➢ Methods declared as static have several restrictions:


• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.

Example:
public class Example
{
// Static variable
static int sVar = 100;

// Instance variable
int iVar = 200;

// Static method
public static void sMethod()
{
System.out.println("Inside sMethod:");
System.out.println("Static variable value: " + sVar);
}

public static void main(String[] args)


{
// Accessing static method directly
Example.sMethod();

// Creating an object of the class to access instance method and variable


Example obj = new Example();
obj.iMethod();
}

// Instance method
public void iMethod()
{
System.out.println("Inside iMethod:");
System.out.println("Instance variable value: " + iVar);
System.out.println("Static variable value: " + sVar);
}
}

(4)STATIC CLASSES
➢ A class can be made static only if it is a nested class.

➢ We cannot declare a top-level class with a static modifier but can


declare nested classes as static. Such types of classes are called Nested
static classes.

➢ Nested static class doesn’t need a reference of Outer class. In this case, a
static class cannot access non-static members of the Outer class.

// A java program to demonstrate use


// of static keyword with Classes
import java.io.*;
public class Example
{
private static String str = "Government Polytechnic - Rajkot";
// Static class
static class MyNestedClass
{
// non-static method
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
Example.MyNestedClass obj
= new Example.MyNestedClass();
obj.disp();
}
}

❖ WHEN TO USE STATIC VARIABLES AND METHODS?


Use the static variable for the property that is common to all objects. For
example, in class Student, all students share the same college name. Use static
methods for changing static variables.
Consider the following java program, that illustrates the use of static keywords
with variables and methods.

// A java program to demonstrate use of


// static keyword with methods and variables

// Student class
class Student {
String name;
int rollNo;
// static variable
static String cllgName;

// static counter to set unique roll no


static int counter = 0;
public Student(String name)
{
this.name = name;
this.rollNo = setRollNo();
}
// getting unique rollNo
// through static variable(counter)
static int setRollNo()
{
counter++;
return counter;
}

// static method
static void setCllg(String name) { cllgName = name; }

// instance method
void getStudentInfo()
{
System.out.println("name : " + this.name);
System.out.println("rollNo : " + this.rollNo);

// accessing static variable


System.out.println("cllgName : " + cllgName);
}
}
// Driver class
public class StaticDemo {
public static void main(String[] args)
{
// calling static method
// without instantiating Student class
Student.setCllg("XYZ");
Student s1 = new Student("Alice");
Student s2 = new Student("Bob");
s1.getStudentInfo();
s2.getStudentInfo();
}
}

You might also like