$ javac ArrayListTest.java
$ java ArrayListTest
$ cat ArrayListTest.java
import java.io.*;
import java.util.*;
public class ArrayListTest{
public static void main(String[] args) {
try {
String hello ="oeoaseu oeu hsoae sthoaust hoaeut hoasntu";
ArrayList<String> appendMe = null;
for(String s : hello.split(" "))
appendMe.add(s+" ");
for(String s : appendMe)
System.out.println(s);
//WHY DOES IT NOT PRINT?
}catch(Exception e){
}
}
}
views:
192answers:
4You need to initialize appendMe.
appendMe = new ArrayList<String>();
When you try to call appendMe.add()
a NullPointerException
is thrown, as you set it explicitly to null
, so execution is jumping straight to the catch block and that second for loop isn't even running. However, you catch all Exceptions silently, so the error isn't displayed. You should probably not have that global try/catch there; at the very least, add an e.printStackTrace();
to the catch block so exceptions aren't just silently ignored
Writing code with empty catch
blocks is very bad practice. Don't get in the habit of doing that. Although suihock captured the root cause of your problem, if you had printed the exception in the catch block:
} catch (Exception e) {
System.out.println("Got an exception: " + e.getMessage());
}
... you would have immediately found the cause of your problem.
First, you are enclosing your code in a try/catch
block but you are swallowing the exception which is a VERY BAD practice. Don't do this, this is actually the reason why you don't get any useful message here. So either log the exception or print e.printStackTrace
in the catch
block or just remove the try/catch
, there aren't any checked Exception
to catch.
Second, you should program to interfaces, not concrete classes (this way, you can change the concrete implementation without modifying the whole code). So, instead of:
ArrayList<String> appendMe;
declare:
List<String> appendMe;
Third, you need to initialize appendMe
somewhere (this is actually the root cause of the malfunction and causes later a NullPointerException
), for example when declaring it:
List<String> appendMe = new ArrayList<String>();
Finally, I recommend to use brackets in your loops, even if there is a single line.
To summarize:
import java.io.*;
import java.util.*;
public class ArrayListTest{
public static void main(String[] args) {
String hello ="oeoaseu oeu hsoae sthoaust hoaeut hoasntu";
List<String> appendMe = new ArrayList<String>();
for(String s : hello.split(" ")) {
appendMe.add(s+" ");
}
for(String s : appendMe) {
System.out.println(s);
}
}
}