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

Advantages and disadvantages of static variable in Java.

I'm new in java and i want to know what are the benefits of using static variables and what are some disadvantages of it?

2 Answers

Hey Jose,

It's not really a matter of advantage or disatvantage, rather than what you need at the moment. Making those decisions will come to you with time and practice but basically you need to know what the main difference is.

The static variables/methods belong to the class rather than an instance of the class.

If you have a static variable you can call it directly through the class as it belongs to it.

If the variable is not static it belongs to the instance of the class.

I.E. lets say you want to create a Vehicle class which has a variable color.

If you do a static variable it belongs straight to the vehicle class and you can call it:

public class Vehicle {
public static color = "red";
}

System.out.println(Vehicle.color)

This will return 'red'

If you do not do this as static you need to instantiate the class before calling the variable.

public class Vehicle {
public color = "red";
}
Vehicle car = new Vehicle;
System.out.println(car.color);

Thanks Yani that really clear out my doubts !!