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
Miguel Zegarra
635 PointsWhat is a method, void, static?
I don´t understand those concepts. Can you help me?
2 Answers
Jaspreet Singh
5,207 Pointsevery method has a return type depends upon what type of method we created example
public int method name{ int val=5; return val (this method will return integer variable or value ) }
every method has a return type
void means it will return nothing.
static static variable static method
static means if we want to use static variable or static method we don't need to create a object of that class we can directly use that function.
example
we mostle use math.random(); function
math is a class and random() is a static method because we are directly usin random() function with class name
we never created the obect of math class.
Greg Kitchin
31,522 PointsFor a bit more clarity... Methods are used in object orientated programming to actually do something in code. Whenever you do anything in Java, you are using a method.
A method will always return something, unless it is declared as void, like in the below example. It's changing the value of the variable gear to the provided argument newValue. It's not returning something, but Java will throw an error, cause if void isn't declared, then it'll expect a return statement near the end of the code block.
public void setGear(int newValue) { gear = newValue; }
In contrast, in the below example, we're asking Java to return an int value.
public int getArea() { return width * height; }
Finally, static means that the method is associated with the class, not a specific instance of that class. Basically, it means you can call a static method without having to create an object of the class.