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 Java Objects Harnessing the Power of Objects Constants

Andrei Li
Andrei Li
34,486 Points

What static is actually doing? Just give access globallly?

And it always go final static or it can be only static?

2 Answers

Ronald Williams
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ronald Williams
Java Web Development Techdegree Graduate 25,021 Points

Static is used to save memory or so you can make something that will be the same for all objects. To understand static you can think in terms of creating objects. Let's say you have an object representing a Student in a university database.

public class Student() {
    int studentNumber;
    String name;
    String university = "Treehouse";

    public Student(int studentNumber, String name) {
        this.studentNumber = studentNumber;
        this.name = name;
    }
}

Now when you go and make a Student, each student will have their own String university = "Treehouse" created. But instead you could make your own application more memory efficient if you made the String university = "Treehouse" static. Then the static string only gets memory once when the application is ran and the Student class loads compared to every single time a student is made.

Here is how Oracle describes it "Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class."

https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html