This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
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
You simply have to initialize your destination array with :
String[] s = new String[a.length];
If you didn't do that, when you try to add something to that array you obtain a NullPointerException.
You have not initialized your array. Try doing
String s[]= new String[a.length];
Related
This question already has answers here:
IndexOutOfBoundsException when adding to ArrayList at index
(10 answers)
Closed 1 year ago.
This is what printed out in the console while I tried to run the code below, I can not tell why the code is not compiling, and I do not see any issues. Please help!! Thanks.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.set(ArrayList.java:441)
at Example.main(Example.java:9)
import java.util.*;
public class Example {
public static void main(String[] args) {
List<String> bucketList = new ArrayList<>();
bucketList.add("Visit Alaska");
bucketList.add("Visit Hawaii");
bucketList.set(2, "Visit Japan");
for (String list : bucketList) {
System.out.print(list);
}
Set<String> codingJournal = new LinkedHashSet<>();
codingJournal.add("2/10/2021");
codingJournal.add("5/8/2021");
codingJournal.add("7/31/2021");
for (String journal : codingJournal) {
System.out.print(journal);
}
Map<String, ArrayList<String>> BU = new HashMap<>();
ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("SQL");
ArrayList<String> classes = new ArrayList<>();
classes.add("CS520");
classes.add("CS669");
BU.put("Languages", languages);
BU.put("Classes", classes);
System.out.println(BU.get("Classes"));
}
}
You can have a look what the exception actually says:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds
...
...
java.base/java.util.ArrayList.set(ArrayList.java:441) at Example.main(Example.java:9)
If you look at line number 9 in your Example.java class, you'll see, you're setting "Visit Japan" in the index no 2 of bucketList:
bucketList.set(2, "Visit Japan");
Where bucketList was just introduced and only 2 elements were added before that call:
List<String> bucketList = new ArrayList<>();
bucketList.add("Visit Alaska");
bucketList.add("Visit Hawaii");
Why is that?
If you look at the implementation of the ArrayList, you'll understand why. When you initialized an ArrayList, this is what is called:
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
where the DEFAULTCAPACITY_EMPTY_ELEMENTDATA is:
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = new Object[0];
If an add(Object obj) is called, then the following implementation is found in ArrayList class:
public boolean add(E e) {
++this.modCount;
this.add(e, this.elementData, this.size);
return true;
}
where this.add(...) says:
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length) {
elementData = this.grow();
}
elementData[s] = e;
this.size = s + 1;
}
So I think you can guess what is happening here. Your list was an array of default of size 0 when it was initialized and modified afterwards, in fact, with the add of new elements, the array size grow(). Let's see what this grow() does:
private Object[] grow() {
return this.grow(this.size + 1);
}
private Object[] grow(int minCapacity) {
return this.elementData = Arrays.copyOf(this.elementData, this.newCapacity(minCapacity));
}
So, you see, it creates an new Array with the capacity of new size.
So, when you've added first two elements, you've created an array of length 2 for your use. That is why whenever you're trying to set bucketList.set(2, "Visit Japan");, you're trying to access the index no 2 of an zero indexed array of length 2, which is obviously not in bound. Hence the ArrayIndexOutOfBoundException is thrown.
This question already has answers here:
Java ArrayList copy
(10 answers)
Closed 4 years ago.
import java.util.*;
public class Metodo {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
a.add(5);
Metodo.inverte(a);
for(int i=0; i<a.size(); i++) {
System.out.println(a.get(i));
}
}
public static void inverte(ArrayList<Integer> a) {
ArrayList<Integer> other = new ArrayList();
other = a;
for(int i=0; i<a.size(); i++) {
a.set(i, other.get(other.size()-i-1));
}
}
}
This method should ivert the numbers in the ArrayList so it should print "5 4 3 2 1" but it prints "5 4 3 4 5" instead. Why?
other = a;
does not create a copy of the original List.
Both a and other reference the same List object, so when you call a.set(0,other.get(other.size()-1), you lose the original value of other.get(0).
You should use:
ArrayList<Integer> other = new ArrayList<>(a);
to create a copy of the original List and remove other = a;
Eran already answered this question, but a simple note here. that you can reverse ArrayList using:
Collections.reverse(arrayList)
You can add the items of a into other in the reverse order and return the result:
public static ArrayList<Integer> inverte(ArrayList<Integer> a) {
ArrayList<Integer> other = new ArrayList<>();
for(int i = a.size() - 1; i >=0 ; i--) {
other.add(a.get(i));
}
return other;
}
So you do:
a = Metodo.inverte(a);
As you can see in answers made, you can learn two things about your programing language:
What is the difference between a copy and a reference? See #Eran's answer
If you change the order of the items in a list when you make a loop on it, you will encounter problems.
How standard libraries and built-in types can help you? See #Mahmoud Hanafy's answer
You need to spend time to know what the language and its ecosystem can afford to you. For instance, it is very important you understand that reverse a collection is something very common, and on every new line you have to ask you: how other developers handle this.
I am trying to add two string using char array but it is not working. Does array changes size? please help with this problem:
public class shift {
String name = "piyush";
public void appends(String lastnaem) {
char a[] = new char[20];
System.out.println(a.length);//printing lenth of array
a = name.toCharArray();//lastnaem.toCharArray();
System.out.println(a.length);//printing length of array after adding string
char v[] = lastnaem.toCharArray();
// for(int i=0;i<v.length;i++) {
// a[6+i]=v[i];
// }
}
public static void main(String[] args) {
shift s = new shift();
s.appends("verma");
}
}
The output is:
20
6
No, the size of the array does not change. When you write a = name.toCharArray() you simply create a completely new array with a new size and assign it to a.
The array a points to changes and the new array a points to has a different length than the original one.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Suppose area1 has three contents 2,3,4, area2 has three contents 1,2,3 and area3 has two contents 1,2. m is the map that keys are locationid and values are list of contentid. For example, area1 has the map (1,{2,3,4}). Each area choose 1 content and find all the combination. I use dfs (recursion) to solve this problem but there is a nullpointerexception in line1. The intermediate is a list of string and i iterate through the list and their types are both string, why there is a null pointer exception? This is a specific condition in nullpointerexception and it is not duplicate.
public static List<String> dfs(String digits,Map<String, List<String>> m) {
List<String> result = new ArrayList<String>();
if(digits.length() == 0){
return result;
}
if(digits.length() == 1){
return m.get(digits.charAt(0));
}
List<String> intermediate = dfs(digits.substring(1, digits.length()),m);
for(String first : m.get(Character.toString(digits.charAt(0)))){
for(String rest : intermediate){ // line1
result.add(first + rest);
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String digits="123";
Map<String,List<String>> selected=new HashMap<>();
selected.put("1", new ArrayList<>(Arrays.asList("4","2","3")));
selected.put("2", new ArrayList<>(Arrays.asList("1","2","3")));
selected.put("3", new ArrayList<>(Arrays.asList("1","2")));
dfs(digits,selected);
}
I guess the problem is here:
return m.get(digits.charAt(0));
it should return null, since digits.charAt(0) is not a String
you need to use substring or Character.toString( here to extract the number
The test code below leads to a "null pointer deference" bug on a String Array(on line 6). This leads to a NullPointerException.
public class TestString {
public static void main (String args[]) {
String test [] = null;
for (int i =0; i < 5; i++) {
String testName = "sony" + i;
test [k] = testName;
}
}
}
-- How do I fix this?
-- What is it that causes this bug?
Thanks,
Sony
You need to initialize your array like this, before :
test = new String[5];
Whenever you use an array, the JVM need to know it exists and its size.
In java there are many way to initialize arrays.
test = new String[5];
Just create an array with five emplacements. (You can't add a sixth element)
test = new String[]{"1", "2"};
Create an array with two emplacements and which contains the values 1 and 2.
String[] test = {"1", "2"};
Create an array with two emplacements and which contains the values 1 and 2. But as you noticed it must be donne at the same time with array declaration.
In Java arrays are static, you specify a size when you create it, and you can't ever change it.
There are too many errors in your code.
1) What is k?
2) You need to initialize the test array first.
String test[] = new String[5]; // or any other number
You are not initializing your array. On the third row you set it to null and then on the sixth row you're trying to set a string to an array that does not exists. You can initialize the array like this:
String test [] = new String[5];
Change String test[] = null; to String test[] = new String[5];
an array must be initialized.
See: http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html