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

Julie Austin
Julie Austin
1,322 Points

non static variable and static context?

I'm so confused. What is the static context? What was the non-static variable? I'm on like my 6th play through and I still don't understand what he's saying!!

1 Answer

Hi Julie,

I know this question was asked some time ago and you may have found your answer already, but for the sake of anyone else looking at this, here is the explanation that helped me.

A non-static variable is a variable within a class that REQUIRES an instance of the class (an object) to be created to use it. A static variable is a variable within a class that DOES NOT REQUIRE an instance of the class (an object) to be created.

class Leggos {
     static int blueLeggos = 10;
     int redLeggos = 15;

Refer to the class, Leggos, that I just specified. Let's look at the redLeggos variable first. If I want to use redLeggos and display it in my program, I first will have to create an instance (object) of Leggos.

Leggos boxOfRedLeggos = new Leggos();
System.out.println("There are %d red leggos in this box!", boxOfRedLeggos.redLeggos);

Now, let's look at the blueLeggos variable. If we want to use blueLeggos and display it anywhere in our program, instead of having to create a new Leggos object first, we can simply display or obtain the amount of blueLeggos whenever we want, because it is associated with the entire Class, Leggos, not an instance of the Class.

System.out.println("There are %d blue leggos in this box!", Leggos.blueLeggos);

I hope that this helps.