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

Why and what is Static used for in Java

When you have a line of code in Java like this: private static final int MAX_PEZ = 12; What does static do for you, why is it helpful?

2 Answers

Generally speaking, the "static" keyword means that the method or variable marked with the "static" keyword belongs to that class, and you don't need an instance of that class to call upon that specific method or value.

Here's a few examples: First I'm going to show what is needed to call a non-static method from within a static context:

public class Test {
    public static void main(String[] args) {
        Test t = new Test(); //I have to create a static Test instance variable
        t.doStuff(); //then I call the non-static doStuff() method off of that static Test instance variable
    }

    public void doStuff() { //notice that the doStuff() method is not static
        System.out.println("test");
    }
}

The compiler would've spat out an error at me if I didn't add the "Test t = new Test()" and called the doStuff() method off of that Test instance variable.

Now if the doStuff() method is declared as "static" this is all this is needed to run it within Main():

public class Test {
    public static void main(String[] args) {
        doStuff(); //no Test instance variable is needed to call the now static doStuff() method
    }

    public static void doStuff() { //notice that the doStuff() method is static 
        System.out.println("test");
    }
}

I hope this helps, let me know if you're still confused and I can try to re-explain a different way.

Do you gain any additional functionality from the static keyword. (Like other classes and methods can access it)?

Well, for other classes and/or methods that can access a static method for example, really depends on not if the method is static itself, but, the access modifier you assign to said method (i.e. default, public, private, or protected).

Thank you.