0

I have splited a string and from the recieved string i am trying to form a word everything is comming fine but everytime i get null string in the first index why?

Here is my code:

    String assetClasses = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
    String[] splits = assetClasses.toString().split(":");

    //System.out.println("splits.size: " + splits.length);
    String ab = null;
for(int i=0; i<splits.length;i++){
    System.out.println(splits[i]);
    ab+=splits[i];
}
System.out.println(ab);

The output:

Gold Stocks Fixed Income Commodity Interest Rates

nullGoldStocksFixed IncomeCommodityInterest Rates

silverFoxA
  • 4,549
  • 7
  • 33
  • 73

4 Answers4

5

Change String ab = null; to String ab = "";

As a complement, see Concatenating null strings in Java to know what's happening when you use String ab = null;

Community
  • 1
  • 1
JFPicard
  • 5,029
  • 3
  • 19
  • 43
  • 3
    @Hell: As a minor note, although the above will work, when concatenating strings it is recommended you use `StringBuilder`. – npinti Apr 17 '15 at 13:10
  • ohh thanks this works for me and i just need the datestring to be one to place it as unique id in my database – silverFoxA Apr 17 '15 at 13:11
1

It gives null because in java's String class below is the implementation of valueOf api of String class.

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
}
Archana Mundaye
  • 523
  • 1
  • 5
  • 19
0

Also - String is immutable, so you're creating lot's of unnecessary objects during this method execution. Use mutable StringBuilder instead:

    String assetClasses = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
    String[] splits = assetClasses.split(":");

    StringBuilder ab = new StringBuilder();
    for (int i = 0; i < splits.length; i++) {
        System.out.println(splits[i]);
        ab.append(splits[i]);
    }
    System.out.println(ab.toString());
RichardK
  • 3,228
  • 5
  • 32
  • 52
0

Let me stress on what npinti said. Strings are immutable in java. Which means every time you say ab+=splits[i]; you are creating a new string. Which is a really slow and inefficient process.

Instead, you can;

String assetClasses = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
String[] splits = assetClasses.toString().split(":");

//System.out.println("splits.size: " + splits.length);
StringBuilder ab = new StringBuilder();
for(int i=0; i<splits.length;i++){
    System.out.println(splits[i]);
    ab.append(splits[i]);
}
System.out.println(ab.toString());

Its that simple!

Community
  • 1
  • 1
Sampath
  • 1,144
  • 1
  • 21
  • 38