This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes ways of instantiation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ways of instantiation" Watch "ways of instantiation" New topic

ways of instantiation

Jeevan Reddy
Ranch Hand

Joined: Nov 10, 2009
Posts: 142

I was asked this question which I could not answer.
What are the different ways of instantiation in Java?

One of the ways is using "new" and I stopped at that saying I was not sure.

If anyone has an idea please clarify.


SCJP 1.6 (94%)
Karthik Shiraly

Joined: Apr 04, 2009
Posts: 711


1) Class.newInstance() [reflection API] is another method. ex: Object o = Class.forName("someclass").newInstance();

2) Object.clone() creates instances.

3) Autoboxing of primitive types creates instances. ex: Integer n = 25000;

4) ObjectInputStream.readObject() also creates instances, but its implementation probably involves reflection itself.
Jeevan Reddy
Ranch Hand

Joined: Nov 10, 2009
Posts: 142
Thanks Karthik, that is really helpful
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 44563
Please search for this; such a question comes up frequently. Particularly in the "beginning Java" forum, where I shall take the liberty of moving this thread (I hope you don't mind, Henry).

Two more examples:
  • A String like "Campbell" is an object in its own right.
  • An array initialiser, eg int[] numbers = {1, 2, 3};
    I agree. Here's the link:
    subject: ways of instantiation
    It's not a secret anymore!