-1

When this code is run, it outputs nullhi. Why is it doing this?

public static void main(String[] args) {
    String[] a = new String[1];
    String m = null;
    String c = "hi";
    for (int i = 0 ; i < c.length() ; i++){
        a[0] = a[0] + c.charAt(i);  
    }
    System.out.print(a[0]);
}
Nic
  • 6,211
  • 10
  • 46
  • 69
Angelb
  • 11
  • 1
  • 1
  • Relevant: http://stackoverflow.com/questions/3426843/what-is-the-default-initialization-of-an-array-in-java – Oli Mar 16 '15 at 14:30

3 Answers3

4

Before the loop, write:

a[0] = "";

i.e.

public static void main(String[] args) {
String[] a= new String[1];
String m = null;
String c = "hi";

a[0] = "";

for (int i=0 ; i<c.length() ; i++){
    a[0]=a[0]+c.charAt(i);  
}

System.out.print(a[0]);

}
Dermot Blair
  • 1,600
  • 10
  • 10
  • @Angelb - In addition, the variable `a` does not need to be an array. You may have heard that Java Strings are immutable. This is true. However, in the expression `String a = ""`, the variable `a` is not a String -- it is a mutable reference to a String. – Andy Thomas Mar 16 '15 at 14:47
0

Do this

    for (int i=0 ; i<c.length() ; i++){
      a[i] = "";
      a[i]= c.charAt(i);  

    }

what you are doing is

for (int i=0 ; i<c.length() ; i++){
    a[0]=a[0]+c.charAt(i);  // a[0] is null, 
}
Muneeb Nasir
  • 2,414
  • 4
  • 31
  • 54
-1

Test if string is null

a[0] = ((a[0] == null) ? "" : a[0] ) + c.charAt(i);
Rene M.
  • 2,660
  • 15
  • 24
  • `a[0]` will always be `null` until it is explicitly changed. That is how object arrays are initialized. – Oli Mar 16 '15 at 14:31
  • Whats going on here? This solution removes the null in the output because a[0] is checked on null. Learn programming before downvoting correct answers – Rene M. Mar 16 '15 at 14:46
  • I didn't downvote you, but why not just have `a[0] = "";` before the loop instead of checking it every time? – Oli Mar 16 '15 at 14:49
  • Both correct and not the question. All fine, only understand sometimes not the reactions of people here. I think twice before I don't vote something. – Rene M. Mar 16 '15 at 15:14