Print all binary strings of length n
Is there any way to make this shorter or more efficient?


Yes, we can do some things.

for(int i = 0; i &lt; Math.pow(2,n); i++)


You calculate the pow for every iteration. The pow call takes some time (compared to basic things like multiplication or addition), you should do it only once.

B = "";
B = '1'+B;
B = '0'+B;


You will create a lot of string copies for every string concatenation. This costs a lot of perfomance. In general, you should use a StringBuilder.
In this special case, we could even use a char array.

for(int i = 0; i &lt; Math.pow(2,n); i++)
if (temp%2 == 1)
temp = temp/2;


You could use bit manipulations. But depending on the jvm or hotspot compiler, this will be done anyway.

void printB(int n)
        B = "";
        int temp = i;


Overall point: avoid abbreviations.



All together, it could be like this:

void printAllBinaryUpToLength(final int length) {
    if (length &gt;= 63)
        throw new IllegalArgumentException("Current implementation supports only a length &lt; 63. Given: " + length);
    final long max = 1 &lt;&lt; length;
    for (long i = 0; i &lt; max; i++) {
        long currentNumber = i;
        final char[] buffer = new char[length];
        int bufferPosition = buffer.length;
        while (bufferPosition &gt; 0) {
            buffer[--bufferPosition] = (char) (48 + (currentNumber &amp; 1));
            currentNumber &gt;&gt;&gt;= 1;
        }
        System.out.println(buffer);
    }
}


Calculates (without printing, printing takes the great majority of every loop) results up to 25 (2^25 = ~33*10^6) in less than a second. Should be enough.