Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Xuanzheng Lin
Xuanzheng Lin
2,466 Points

Hey guys, I am new to Java. I am curious what the meaning of public class and public status void ... in every code?

Like: public class Example {

public static void main(String[] args) { }

}

3 Answers

Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

Of course!

variables that are static state that are automatically "class variables" as we use to call them. which means for example that when you are about lets say to instantiate an object of type User inside the main method to have access to User variables and methods you are doing something like this.

public static void main(String[] args) {
         public User usr1 = new User();
    }

Now you have access to all the variables and methods with the object usr1. You cannot have access otherwise.

But, if you make a method of the class User static. for example inside the User class, we have a method called displayName(); and we declare it as static.

public static String displayName() {
 return name;
}

Now, in the main method we can access this method without instantiate an object of that class as we did previously. you can now access that method like this:

System.out.println(User.displayName());
Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

You can access that method simply by using the name of the class only.

Konstantinos Pedarakis
Konstantinos Pedarakis
21,301 Points

hello Xuanzheng Lin

Public in general means that the method or variable can be accessed from anywhere in you code. public static void in a method means several things, first of all public as said previously, the method can be accessed from anywhere in you code, static means that you can call this method as a class variable without make an instance of that class and finally void means that the method does not return anything, it simple process something and then end its execution.

Happy learning and coding! :)

Xuanzheng Lin
Xuanzheng Lin
2,466 Points

Hey Konstantinos,

Thank you so much for the detailed explanation. I wonder do you mind to clarify the word static a little more. Very muc appreciated!

Have a good one : )

Xuanzheng Lin
Xuanzheng Lin
2,466 Points

Gotcha! Thank you so much : ) Have a good one!