Question

I'm experiencing a strange issue using the append() method of StringBuilder class; here is the method:

public StringBuilder toStringBuilder(byte[] b)
{
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < b.length; i++) 
        {
            s.append(Integer.toString((b[i] & 0xff) + 0x100,16).substring(1));
        }
    System.out.println(s);
    return s;
}

It takes a byte array and converts it into a StringBuilder (doing other stuff in the meanwhile).

Everything seems OK, when I run the program it prints the correct result, but shows also a NullPointerException that doesn't let me continue using the program; the exception is pointed to the fourth line

(for (int i = 0; i < b.length; i++))

Here is a screenshot:

Screenshot

Was it helpful?

Solution

If this line:

for (int i = 0; i < b.length; i++) 

throws an NPE, there is only one possible explanation. b is null.

You can prove (or disprove) this by adding this statement immediately before the for statement.

System.out.println("b is " + b);

Once you've confirmed that, you need to work backwards to figure out why the b is null at that point. I can't offer any insights based on the code you've shown us.

OTHER TIPS

its working correctly in my code , check b before processing it for null.

if(b!=null)
{
for (int i = 0; i < b.length; i++) 
        {
            s.append(Integer.toString((b[i] & 0xff) + 0x100,16).substring(1));
        }
}

Try adding () brackets after length like so:

for (int i = 0; i < b.length(); i++) 
        {
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top