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 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