Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

What does the keyword "static" actually do to my code when applied?

What does the keyword "static" actually do to my code when applied?

2 Answers

Thomas Nilsen
Thomas Nilsen
14,957 Points

Here is one answer i gave to another person about static variable inside classes:

One example would be if you want to store a value across several instances. Here is an example:

class Person {
    public static int numberOfPeople = 0;
    private String name;

    {
        numberOfPeople++;
    }

    Person() {
        this.name = "Default Name";
    }

    Person(String name) {
        this.name = name;
    }

}


class Test {
    public static void main(String[] args) {
        Person p1 = new Person("Mark");
        Person p2 = new Person("Joe");
        Person p3 = new Person();

        //This will print 3
        System.out.println(Person.numberOfPeople);
    }
}
Baljot Malhi
Baljot Malhi
3,953 Points

Simply you can put static keyword is something which could be accessed without instantiating. Static methods could be called without making a object or instantiating you can access the static method directly hope this helps you.