Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.