I want to input a string
Suppose the string was :
String s = "sani";

Now I want to make "sani" the name of an object of one of the class.
Suppose the name of the class is myClass.
I want to :

myClass sani = new myClass();

Any ideas??

Recommended Answers

All 5 Replies

Here I will create a class named StringClass and build constructors.....

public class StringClass
   public static String StringAsObject;
   // Defining the new Value of s when calling this method
  StringAsObject = "sani";
   // Building Constructors
    public static String getStringAsObject()
		return StringAsObject;
	public void setStringAsObject(String s)
	StringAsObject = s;


Now I will create a class named myClass that also contains method main and call the value of s which is the string "sani"

public class myClass
	public static void main(String [] args)
	StringClass aString = new StringClass();
	String s;
    s = aString.getStringAsObject();	



If this is not what you were referring to let me know because I am unclear.

Thanks Branderson

StringClass aString = new StringClass();

this is what you wrote but I want it as

StringClass sani = new StringClass();

Is it possible like that .... whenever I input a string it should become the name of an object.

No it's not. The closest thing you'll be able to do is to use a HashMap. Which is a list of key/value pairs. The string would be the key, and the object would be the value.

public class HashTest {
    private HashMap objList;
    private Object obj;
    private String objName;

    public HashTest(){

    public HashTest(int size){
        this.objList = new HashMap(size);

    public void add(Object obj, String name){

    public void remove(String name){
    public Object get(String name){

    public void showObjects(){
         String name;
         ArrayList ar = new ArrayList(this.objList.values());
         for(int i = 0; i < ar.size(); i++){
              name = ar.get(i);
    public static void main(String[] args){
        HashTest test = new HashTest(5);
        String name = "sani";
        Object o = new Object(); // <-- that would be some object you want to name
        String name2 = "mandy";
        Object o2 = new Object();



Try that out, you may need to add some casts and stuff, but you should get the idea.

Okay fren ... but I'll keep on trying ...

hi everyone,
Is this what you mean?

String a = "sani";
Object k;

k = (Object)a;
//k has already been assigned the string "sani"
myClass k = new myClass( );

I hope this helps you

Yours Sincerely

Richard West

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.