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 Java Arrays Iteration Enhanced For Loop

Jun Dong
Jun Dong
4,754 Points

the "new" Keyword

So when we create an object we use the new keyword, and sometimes we don't. Can someone explain what the "new" keyword does?

2 Answers

When you create a object from a class hence

 class SampleClass {

}

SampleClass awesomeClass = new SampleClass();

You are basically creating a template from the main class think of objects as templates from a specific class. new is a Java keyword. It creates a Java object and allocates memory for it on the heap. There is ways to create a object from a class without using the new keyword but it is bad practice, Unless you have specific reasons for not using the new keyword you can always use the newInstance or constructor or even clone ect methods but that might be out of your scope level if you are just getting started with java.

jacobb2
jacobb2
14,128 Points

The new keyword creates a new object that you can use. If you are not using the new keyword, I would guess you are declaring a variable and not using an object.

https://stackoverflow.com/questions/7019754/what-does-the-new-keyword-actually-do-in-java-and-should-i-avoid-creating-new