I was asked following question in an interview : Array a = {1,2,3,4,5}, Array b = {a,b,c,d,e}, write a program to add individual elements of both array and enter the sum in third array with output like {e1, d2, c3, b4, a5}
I was not able to come up with solution at that time and now I am trying at home and wrote following code but got null pointer exception :
public class ArrayMergeIndividualElements {
String[] a = {"1","2","3","4","5"};
String b[] = {"a","b","c","d","e"};
String s[]=null;
void mergeArrays()
{
int k=0;
int j=b.length-1;
for(int i=0;i<a.length;i++)
{
for(;j>=0;)
{
System.out.println("Number array is "+a[i]);
System.out.println("String array is "+b[j]);
s[k]=a[i]+b[j]; //getting null pointer exception at this line
k++;
j--;
break;
}
}
System.out.println("output is :");
for(int l=0;l<s.length;l++)
{
System.out.print(s[l]);
}
}
public static void main(String[] args) {
ArrayMergeIndividualElements amie = new ArrayMergeIndividualElements();
amie.mergeArrays();
}
}
I have tried following code by searching on stackoverflow , but no luck String[] both = Stream.concat(Arrays.stream(a[i]), Arrays.stream(b[j])) .toArray(String[]::new);
Individually arrays are printing the value but when I try to add/concatenate them I am getting null pointer.
Also can we add both arrays if one is Integer array and other is String array?
Please help