File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Create object Without new operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Create object Without new operator" Watch "Create object Without new operator" New topic

Create object Without new operator

Manoj Paul
Ranch Hand

Joined: Jan 18, 2007
Posts: 110
Here is my program.
An object 'object' is created using the new operator.
I want to create an object without using the new operator.
Can you suggest how?




public class AQuestion7
String name="Manoj Kumar Paul";

public void check()
System.out.println("Substring = "+name.substring(0));
System.out.println("Substring = "+name.substring(9));
System.out.println("Substring = "+name.substring(0,5));

System.out.println("My name is = "+name);

public static void main(String args[])
AQuestion7 object = new AQuestion7();

Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
You can you reflection to create objects without the new operator.

Rahul Bhattacharjee
LinkedIn - Blog
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

substring returns a new Object
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

Not an advanced question. Moving...

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 36508
Originally posted by Manoj Paul:
String name="Manoj Kumar Paul";
That's one way of doing it; the String literal is an object in its own right.
So would "Integer i = 123;" using autoboxing (Java 5 and 6 only).

As David O'Meara told you, a lot of the String class methods create a new object.
You can create arrays with an initialiser:-
int[] myArray = {1, 2, 3, 4, 5};

The commonest way, as suggested by Rahul Bhattacharjee, is to use a factory method. One way is to use the Class.forName("").newInstance() syntax, but I think it needs a no-argument constructor to work properly.

There are probably others; this question has come up before on these boards. Try a search for it.
Ramu Valivarthi
Ranch Hand

Joined: Apr 24, 2007
Posts: 37

you can create object without using 'new'.in several ways.

1:using factory methods.
2:using cloneable
3:using newInstance().
Rahul Bhattacharjee
Ranch Hand

Joined: Nov 29, 2005
Posts: 2308
Originally posted by Ramu Valivarthi:
you can create object without using 'new'.in several ways.
1:using factory methods.

what is it ?
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24166

Apparently continued here.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: Create object Without new operator
Similar Threads
Strings and mutablelity
Without new operator
Without new operator
Create object Without new operator
Capitalize first letter in string