Krishna
Krishna

Reputation: 621

Not able to add object to non-primitive array

this is test class. here I'm trying to add string to string array. I cannot use ArrayList here in my case. So please give me a solution.

public class Test {

String[] name = new String[10];

public void addName(String sName){
    for(String s : name){
        if(s==null){
            s = sName;
            break;
        }
    }
}

public void displayString(){
    for(String s : name){
        System.out.println(s);
    }
}
}

this is main class

public class TestDemo {

public static void main(String[] args) {
    Test t = new Test();
    t.addName("prasad");
    t.addName("ravi");
    t.addName("john");

    t.displayString();
}

}

the out put to displayString is null

Upvotes: 0

Views: 68

Answers (3)

jonhid
jonhid

Reputation: 2135

Someting like this should work

public void addName(String sName){
    for(int i=0; i<name.length; i++){
        if(name[i]==null){
           name[i] = sName;
           break;
        }
   }

}

Upvotes: 1

M_G
M_G

Reputation: 352

Think of s as a variable to which the value of name[index] is copied. Assigning a value to s would not change the value of name[index].

Try:

public void addName(String sName){
    for (int i = 0; i < name.length; i++) {
        if (name[i] == null) {
            name[i] = sName;
            break;
        }
    }
} 

Upvotes: 3

Yoav Gur
Yoav Gur

Reputation: 1396

s = sName assigns the value to the local variable, which used to hold the same value as the Nth member of the array, but uses a different place in the memory.
Long story short, when s is updated, the array element is not.

Try this:

public void addName(String sName){
    for(int i= 0; i < name.length; i++){
        if(name[i]==null){
            name[i] = sName;
            break;
        }
    }
}

Upvotes: 4

Related Questions