I am new to JAVA and found some of its concepts very irritating and no matter how hard I try I can not find suitable explanation for this behavior…of course there are wor around for these problems but still I want to know am I missing something very simple here or JAVA is like this???
- I have a string array in one of my class A and I want it to be filled through a method of another class B…so I create an object of class B into A and call the method B.xyz and equate it to the string arra but BOOM I can’t do it….java throws a nullpointer exception……….I dont know why…
.
public class B{
public void xyz() {
String[] mystrings=new String[70];
for(int i=0;i<5;i++)
mystrings[i]=value;
return mystrings;
}
}
public class A {
public void abc() {
B b=new B();
String[] StringList;
StringList=b.xyz();
System.out.println(StringList.length);
}
}
I have a similar code fragment now sadly the length of the StrinList becomes 70….if I want to print all the strings of this array I dont have any other way….remember even though the size of mystring is 70 in class B only 5 of its components are properly initialized……..SO considering I am in class A and have no way to find out how many times did the for loop in B executed……how do I accurately loop through all the elements of StringList in A………
PS: There are workarounds to solve this problem but I wanted to know why this happens,i.e, why the length attribute doesn’t change according to the components initialized??
If you only need an array of length 5 then only initialize it as that size, e.g.:
If you want an array that you can expand you should consider using
ArrayListinstead. E.g.:Then you can get its size, add to it and print the elements like this:
Hope that helps.