CodeGym /Courses /New Java Syntax /Static variables and methods

Static variables and methods

New Java Syntax
Level 11 , Lesson 2
Available

"Let's move on to a new topic. Now, I'd like to discuss static variables and methods."

"Ellie, I've already learned about static variables and methods. But I'd like to learn more details."

"When we declare variables in a class, we define whether these variables will be created just once, or if each instance (object) of the class will have its own copy. By default, a new copy of a variable is created for each object. This is how it looks:"

Class declaration
class Cat                        // Class
{
    String name;                 // Variable

    Cat(String name)             // Constructor
    {
        this.name = name;        // Variable initialization
    }
}
Code in the main method:
Cat cat1 = new Cat("Oscar"); // Create one object whose name variable contains "Oscar"
Cat cat2 = new Cat("Missy"); // Create one object whose name variable contains "Missy"
System.out.println(cat1.name);
System.out.println(cat2.name);
Screen output
Oscar
Missy

"Despite being declared in the same class (Cat), the variables cat1.name and cat2.name contain different values because they reference different objects."
"That makes sense."
"However, only one copy of a static variable exists for every instance of a class, and it must be accessed using the class name."

Class declaration
class Cat                   // Сlass
{
    String name;            // Instance (non-static) variable
    static int catCount;    // Static variable

    Cat(String name)
    {
        this.name = name;
        Cat.catCount++;   // Increment the static variable by 1
    }
}
Code in the main method:
System.out.println(Cat.catCount);
Cat cat1 = new Cat("Oscar");

System.out.println(Cat.catCount);
Cat cat2 = new Cat("Missy");

System.out.println(cat1.name);
System.out.println(cat2.name);
System.out.println(Cat.catCount);
Screen output:
0
1
Oscar
Missy
2

"OK, that also makes sense."

"Java methods are divided into two categories. Instance methods are called on an object and have access to that object's data. Static methods don't have that access, since they simply don't have an object reference. However, they can reference the class's static variables and other static methods.

Static methods can't address non-static methods or non-static variables!"

"Why is that, Ellie?"

"Each instance variable is contained in an object. It can be accessed only if you have a reference to that object. No such reference is available to a static method."

"Do instance methods have such a reference?"

"Yes, it is passed to instance methods indirectly. A reference to the object on which an instance method is called is indirectly passed to the instance method. The variable that stores this reference is called this. This allows the method to always access the object's data or call another non-static method on the same object.

Instead of an object reference, null is passed to static methods. That's why they can't address non-static variables and methods. They simply don't have a reference to an object associated with these variables and methods."

"OK, Ellie, I understand that."

"This is how non-static methods work:

What the code looks like
Cat cat = new Cat();
String name = cat.getName();
cat.setAge(17);
cat.setChildren(cat1, cat2, cat3);
What really happens
Cat cat = new Cat();
String name = Cat.getName(cat);
Cat.setAge(cat, 17);
Cat.setChildren(cat, cat1, cat2, cat3);
When you call a method using <object> dot <method name>, you're actually calling a class method and passing that same object as the first argument. Inside the method, the object is called 'this'. All operations in the method are performed on this object and its data."

"Here's how static methods work:

What the code looks like
Cat cat1 = new Cat();
Cat cat2 = new Cat();
int catCount = Cat.getAllCatsCount();
What really happens
Cat cat1 = new Cat();
Cat cat2 = new Cat();
int catCount = Cat.getAllCatsCount(null);
When you call a static method, no object is passed to it. In other words, 'this' equals null. That's why a static method can't access non-static variables and methods (since it has nothing to implicitly pass to non-static methods)."

"A variable or method is static if it has the keyword static in front of it."

"Why are such methods needed if they are so severely limited?"

"Well, such methods do have their benefits."

"First, we don't have to pass an object reference to use static methods and variables."

"Second, it is sometimes necessary to have one and only one copy of a variable. For example, System.out (the static out variable of the System class)."

"Third, sometimes you need to call a method before you are able to create objects."

"Ellie, can you give me an example of this?"

"Why do you think the main() method is static? It's static so the programmer can call it immediately after loading a class into memory, before any objects have been created."

Comments (35)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Fadhil Radhian Level 18, Semarang, Indonesia
24 March 2023
deep yet explained in simple terms. Amazing!
Thomas Level 13, Scottsdale, United States
29 November 2021
that's a mighty fine explainer ! -- including more context on why / how -this- exists in the language. Code Gym has so many 'nuggets' like this compilation.
Hisham Thabet Level 8, Lahj, Yemen
11 August 2021
For more understanding You can watch this video : Static methods and veriables
amj Level 7, Imphal , India
21 August 2020
When we declare variables in a class, we define whether these variables will be created just once, or if each instance (object) of the class will have its own copy. By default, a new copy of a variable is created for each object. This is how it looks:" tell me the simplest
Maryem Vickers Level 7, HT..., United Kingdom
29 August 2020
You decide if the variable will be created for ONE object or each of the objects. Do you get it now?!
Diego Ortiz Level 8, Lima
16 June 2021
Each time an object is created its own variables are created, i.e, copies of the non-static variables y cada copia pertenece a un único objeto. However, all created objects share a static variable. It would be something like non-static variables belong to objects and static variables to classes. Therefore, to use a non-static variable you do it through an object reference, but a static variable you do it through the class itself.
amj Level 7, Imphal , India
21 August 2020
i cant understand
andy 6473 Level 9, Bangalore, India
18 June 2020
If we are having doubts related to static and non static variables, the code we wrote in the previous example will provide a good idea . where we increment even and odd .
David Level 26, Bucharest, Romania
9 March 2020
Can anyone tell me why is here 2? O know that everytime an object is created, the cat.count is incremented, but there are created only two objects....
Corina Bodea Level 14, Cluj Napoca, Romania
17 March 2020
Indeed :). There are 2 objects created, so that the count is incremented 2 times. You know that a default int value equals 0. Because our static counter (catCount) is an uninitialised int value it means that its default value is 0.

System.out.println(Cat.catCount); // initially our count is 0 
Cat cat1 = new Cat("Oscar");

System.out.println(Cat.catCount); // after creating "Oscar" Cat object count is 1
Cat cat2 = new Cat("Missy");
                           // after creating "Missy" Cat object count is 2
System.out.println(cat1.name);
System.out.println(cat2.name);
System.out.println(Cat.catCount); // and here the count value is printed 
David Level 26, Bucharest, Romania
17 March 2020
Thank you!! I understood, I was confusing th catCount with the index :)
Faisal Ahmed Level 13, Bangalore, India
2 June 2020
* default value of catCount is 0 * first object is created and passed with parameter(when we create an object,by default constructor is called,so catCount is incremented by 1). * second object is created and passed with parameter(again constructor is called,so catCount is incremented by 2).
Ted404 Level 11, Dubai, United Arab Emirates
4 March 2020
So, basically static methods or variables cannot be called instantiated and be called using the objects as they belong to the whole class and thus, they do not have a reference to an object. In other words, it is a kind of Global variable. hmm... is there anything that I missed? Please help is I am thinking wrong.
Nickolas Johnson Level 8, St. Louis, United States of America
13 March 2020
I think so long as you can access the class, you can access its static variables.
Gellert Varga Level 23, Szekesfehervar, Hungary
8 April 2020
I think the same way.:)
Jeremi Nuer Level 7, San Francisco, United States
17 August 2020
I have trouble wrapping my head around some of these concepts... but i think that is correct, and it helped when she explained that system.out and the main method are static, to show examples of when they are used
29 December 2019
so, r u static or non-static!
Зоран Јањић Level 8, Teslic, Serbia
26 October 2019
Anyone can explain more clear to me, don't understand a word here... "Java methods are divided into two categories. Instance methods are called on an object and have access to that object's data. Static methods don't have that access, since they simply don't have an object reference. However, they can reference the class's static variables and other static methods. Static methods can't address non-static methods or non-static variables!"
Thiago Luz Level 6, Sao Paulo, Brazil
2 November 2019
I can try. Let's continue with the example of Cat class from the explanation. Suppose we have a non-static method getName(). When your object call the non-static method, cat.getName(), you pass the object himself as reference, cat.getName(cat). Suppose the reference is a book index and the book is the class. With this reference you can look for non-static variables and non-static methods inside the class. So if you call a static method you don't pass the object as reference. So inside the class you can't find anything. I hope this make things more clear.
Зоран Јањић Level 8, Teslic, Serbia
2 November 2019
Thank you, buddy, appreciate​ it.