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

Joseph Frazer
Joseph Frazer
5,404 Points

Confused with what STATIC is in Java.

Confused with what the static method in Java is. Please help!

2 Answers

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

For now, imagine the static keyword as a way of giving you the ability to have variables and methods that are associated with a class and not an instance of that class. So you never need to use the new keyword to get to the variables, you can access them right off the class.

Here are some examples:

String example = "hello";
// This toUpperCase is on the instance
String anotherExample = example.toUpperCase();

// See how the parseInt method is on the Integer class?  That's because it is static
int num = Integer.parseInt("42");

That help?

Angry Bunny
Angry Bunny
454 Points

nope... (ยด๏ผ›ฯ‰๏ผ›`)๏ฝณ๏ฝฉ๏ฝฉ

Can you give an example of the benefit of using static, and how it would be without static?

A static method is a method that can be used without creating an object that the method belongs to. Example of NON-static method: Suppose your program is a digital library system. It contains books. Each book is an object of the type "book", and each has a method called "countWords" which returns the number of words in the book. To use "countWords", you must have a specific book in mind--e.g. you have "LordOfTheRings" as a type "book" object, and you invoke "LordOfTheRings.countWords".

A static method is one where you don't have to this, one that can be used without having a specific instance of some type in your program. E.g. Java has a library called "Math", with various mathematical functions like sine and cosine. You can use those without having an object of the type "Math"--you just invoke "Math.sin(x)" if you want the sine of x.

Another example is your "main" method ("public static void main(String[] args)"). Let's say this is located in a class called "MyProgram". "main" can be run without creating an object that belongs to the type "MyProgram".