Static Variables and Methods

Static Variables and Methods

Static modifiers has a many special type of methods and variables which is treating as a concepts entirely separate from the other modifiers.the count will just be initialized back to a default value with each new instance. The answer to both the utility method always runs the same scenario and the keep a running total of instances scenario is to use the static modifier. Variables and methods are marked static which is belong to the class, That\'s why we can use static method or variable without having any instances of that class at all. We need only have a class available to be able to invoke a static method or access a static variable.

Static variables : It can be accessed without having an instance of a class. But in this case instance a static variable of a class will be shared by all instances of that class; there is only one copy, That are following in this code.

class Frog {
static int frogCount = 0; // Declare and initialize static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.println(\"Frog count is now \" + frogCount);
}
}

By:UMANG
Date:2025-02-09 00:00:00

Post Your Answers


User Email:

User Name:
Answers:

Related Java Subjective Links

Java Subjective interview questions and answers for experienced and fresher