Some small code-golfing tips
These tips were a bit too small for a separated answers, so I will use this answer for very small codegolfing tips that I found or came up with, and aren't mentioned in the other tips yet:
Removing the last character of a String:
// I used to do something like this:
s.substring(0,s.length()-1) // 27 bytes
// But this is shorter:
s.replaceAll(".$","") // 21 bytes
In some cases you know what the last character is beforehand, and you also know this character only occurs once in the String. In that case you can use .split
instead:
// As example: "100%" to "100"
s.split("%")[0] // 15 bytes
Encoding shortcuts:
// When you want to get the UTF-8 bytes I used to do this:
s.getBytes("UTF-8"); // 20 bytes
// But you can also use "UTF8" for the same result:
s.getBytes("UTF8"); // 19 bytes
All encodings have a canonical name used in the java.nio
API, as well as a canonical name used in the java.io
and java.lang
APIs. Here is a full list of all supported encodings in Java. So always use the shortest of the two; the second is usually shorter (like UTF-8
vs utf8
, Windows-1252
vs Cp1252
, etc.), but not always (UTF-16BE
vs UnicodeBigUnmarked
).
Random boolean:
// You could do something like this:
new java.util.Random().nextBoolean() // 36 bytes
// But as mentioned before in @Geobits' answer, Math.random() doesn't require an import:
Math.random()<.5 // 16 bytes
Primes:
There are a lot of different ways to check for primes or get all primes. @SaraJ's answer here is the shortest for positive integers (\$\geq1\$), and @primo's method is the shortest for integers \$\geq2\$.
// Check if n (≥ 1) is a prime (@SaraJ's method):
n->{int i=1;for(;n%++i%n>0;);return n==i;}
// Check if n (≥ 2) is a prime (@primo's method):
n->{int i=n;for(;n%--i>0;);return i<2;}
These prime checks can be modified to loop over primes. Here doing so with @SaraJ's approach for example:
v->{for(int n=2,i;;){for(i=1;n%++i%n>0;);if(n++==i)/*do something with prime `i` here*/;}}
NOTE: Usually you can merge it with other existing loops depending on how you want to use it, so you won't need a separate method. This saved a lot of bytes in this answer for example.
Integer truncation instead of Math.floor/Math.ceil:
If you are using positive doubles/floats and you want to floor
them, don't use Math.floor
but use an (int)
-cast instead (since Java truncates on integers):
double d = 54.99;
int n=(int)Math.floor(d); // 25 bytes
int m=(int)d; // 13 bytes
// Outputs 54 for both
The same trick can be applied to negative doubles/floats you want to ceil
instead:
double d = -54.99;
int n=(int)Math.ceil(d); // 24 bytes
int m=(int)d; // 13 bytes
// Outputs -54 for both
Use &1
instead of %2
to get rid of parenthesis:
Because the Operator Precedence of &
is lower than default arithmetic operators like */+-
and %
, you can get rid of parenthesis in some cases.
// So instead of this:
(i+j)%2 // 7 bytes
// Use this:
i+j&1 // 5 bytes
Note that this doesn't really help in boolean-checks, because then you'd still need parenthesis, they're just moved a bit:
(i+j)%2<1 // 9 bytes
(i+j&1)<1 // 9 bytes
BigIntegers and creating variables for static method calls:
When using BigIntegers, only create it once which you can then re-use. As you may know, BigInteger contains static fields for ZERO
, ONE
and TEN
. So when you only use those three, you don't need an import
but can use java.Math.BigInteger
directly.
// So instead of this:
import java.math.BigInteger.*;
BigInteger a=BigInteger.ONE,b=BigInteger.ZERO; // 76 bytes
// or this:
java.math.BigInteger a=java.math.BigInteger.ONE,b=a.ZERO; // 57 bytes
// Use this:
java.math.BigInteger t=null,a=t.ONE,b=t.ZERO; // 45 bytes
NOTE: You have to use =null
so t
is initialized in order to use t.
.
Sometimes you can add multiple BigIntegers to create another to save bytes. So let's say you want to have the BigIntegers 1,10,12
for some reason:
// So instead of this:
BigInteger t=null,a=t.ONE,b=t.TEN,c=new BigInteger(12); // 55 bytes
// Use this:
BigInteger t=null,a=t.ONE,b=t.TEN,c=b.add(a).add(a); // 52 bytes
As correctly pointed out in the comments, the trick with BigInteger t=null;
for it's static method calls can also be used with other classes.
For example, this answer from 2011 can be golfed:
// 173 bytes:
import java.util.*;class g{public static void main(String[]p){String[]a=p[0].split(""),b=p[1].split("");Arrays.sort(a);Arrays.sort(b);System.out.print(Arrays.equals(a,b));}}
// 163 bytes
class g{public static void main(String[]p){java.util.Arrays x=null;String[]a=p[0].split(""),b=p[1].split("");x.sort(a);x.sort(b);System.out.print(x.equals(a,b));}}
getBytes()
instead of toCharArray()
When you want to loop over the characters of a String, you'll usually do this:
for(char c:s.toCharArray()) // 27 bytes
// or this:
for(String c:s.split("")) // 25 bytes
Looping over the characters can be useful when printing them, or appending them to a String, or something similar.
However, if you only use the chars for some unicode-number calculations, you can replace the char
with int
, AND you can replace toCharArray()
with getBytes()
:
for(int c:s.getBytes()) // 23 bytes
Or even shorter in Java 8+:
s.chars().forEach(c->...) // 22 bytes
In Java 10+ looping over the character to print can now also be done in 22 bytes:
for(var c:s.split("")) // 22 bytes
Random item from a List
:
List l=...;
// When we have an `import java.util.*;` in our code, shuffling is shortest:
return l.get(new Random().nextInt(l.size())); // 45 bytes
return l.get((int)(Math.random()*l.size())); // 44 bytes
Collections.shuffle(l);return l.get(0); // 39 bytes
// When we don't have an `import java.util.*` in our code, `Math.random` is shortest:
return l.get(new java.util.Random().nextInt(l.size())); // 55 bytes
return l.get((int)(Math.random()*l.size())); // 44 bytes
java.util.Collections.shuffle(l);return l.get(0); // 49 bytes
Check if a String contains leading/trailing spaces
String s=...;
// I used to use a regex like this:
s.matches(" .*|.* ") // 20 bytes
// But this is shorter:
!s.trim().equals(s) // 19 bytes
// And this is even shorter due to a nice feature of String#trim:
s!=s.trim() // 11 bytes
Why does this work, when !=
on Strings is to check for reference instead of value in Java? Because String#trim
will return "A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space." I've used this, after someone suggested this to me, in this answer of mine.
Palindrome:
To check if a String is a palindrome (keeping in mind both even and odd lengths of Strings), this is the shortest (.contains
works here because we know both the String itself and its reversed form are of equal length):
String s=...;
s.contains(new StringBuffer(s).reverse()) // 41 bytes
.contains(...)
instead of .equals(...+"")
thanks to @assylias's comment here.
Either is 0, or both are 0?
I think most already know this one: if you want to check if either a
or b
is zero, multiply instead to save bytes:
a==0|b==0 // 9 bytes
a*b==0 // 6 bytes
And if you want to check if both a
and b
are zero, you could use a bitwise-OR, or add them together if they are always positive:
a==0&b==0 // 9 bytes
(a|b)==0 // 8 bytes (if either `a`, `b` or both can be negative)
a+b<1 // 5 bytes (this only works if neither `a` nor `b` can be negative)
Even = 1, odd = -1; or vice-versa
// even = 1; odd = -1:
n%2<1?1:-1 // 10 bytes
1-n%2*2 // 7 bytes
// even = -1; odd = 1:
n%2<1?-1:1 // 10 bytes
n%2*2-1 // 7 bytes
The reason I add this was after seeing k+(k%2<1?1:-1)
in this answer:
k+(k%2<1?1:-1) // 14 bytes
// This would already have been shorter:
k%2<1?k+1:k-1 // 13 bytes
// But it can also be:
k%2*-2-~k // 9 bytes
Loop n
times in Full Program
If we have a challenge where a full program is mandatory, and we need to loop a specific amount of times, we can do the following:
// instead of:
interface M{static void main(String[]a){for(int n=50;n-->0;)/*do something*/}} // 78 bytes
// we could do:
interface M{static void main(String[]a){for(M m:new M[50])/*do something*/}} // 76 bytes
The same applies when we have to take this range as input:
interface M{static void main(String[]a){for(int n=new Byte(a[0]);n-->0;)/*do something*/}} // 90 bytes
interface M{static void main(String[]a){for(M m:new M[new Byte(a[0])])/*do something*/}} // 88 bytes
Credit to @JackAmmo in this comment.
try-finally instead of try-catch(Exception e), and when/how to use it
If you have to catch and ignore an Exception, in most cases it's shorter to use finally{...;}
instead of catch(Exception){}
. Some examples:
When you want to return the result as soon as you hit an error:
try{...}catch(Exception e){return ...;} // 33 bytes
try{...}finally{return ...;} // 22 bytes
I've used this initially to save bytes in this answer of mine (credit for the indirect golf goes to @KamilDrakari). In this challenge we have to loop diagonally over an NxM matrix, so we have to determine whether the amount of columns or amount of rows is the lowest as our maximum in the for-loop (which is quite expensive in terms of bytes: i<Math.min(a.length,a[0].length)
). So, simply catching the ArrayIndexOutOfBoundsException
using catch-finally
is shorter than this check, and thus saves bytes:
int[] a = ...;
int r=0,i=0;for(;i<Math.min(a.length,a[0].length);)r=...i++...;return r; // 66 bytes
int r=0,i=0;try{for(;;)r=...i++...;}finally{return r;} // 48 bytes
This also works with a void return;
, like this:
try{...}catch(Exception e){} // 25 bytes
try{...}finally{return;} // 21 bytes
Which actually saved an additional byte in that same linked answer above by putting the answer in the very first cell, like @KamilDrakari does in his C# answer as well:
m->{try{for(...);}finally{return;}}
But what about a try-catch where you don't want to immediately return? Unfortunately, you can't have a completely empty finally{}
block as alternative to catch an Exception. You can however still use it inside a loop by using continue
(or break
) as alternatives. Here an example where we want to continue with the next iteration of the loop when an Exception occurs:
for(...)try{...}catch(Exception e){} // 30 bytes
for(...)try{...}finally{continue;} // 28 bytes
I've used this approach in this answer of mine to save 2 bytes.
So when you can use a return
, continue
or break
, it's always better to use try{...}finally{...;}
instead of try{...}catch(Exception e){}
. And in most cases, especially when checking boundaries of matrices, it's shorter to try-finally
any ArrayIndexOutOfBoundsExceptions
, instead of doing manual checks to see whether the indices are still in bounds.
Math.pow(2,n)
When you want a power of 2, a bit-wise approach is much shorter:
(int)Math.pow(2,n) // 16 bytes
(1<<n) // 6 bytes
Combining bit-wise and logical checks instead of using parenthesis
I think it is well-known by now that &
and |
can be used instead of &&
and ||
in Java (boolean) logical checks. In some cases you'd still want to use &&
instead of &
to prevent errors though, like index >= 0 && array[index].doSomething
. If the &&
would be changed to &
here, it will still evaluate the part where it uses the index in the array, causing an ArrayIndexOutOfBoundsException
, hence the use of &&
in this case instead of &
.
So far the basics of &&
/||
vs &
/|
in Java.
When you want to check (A or B) and C
, the shortest might seem to use the bit-wise operators like this:
(A|B)&C // 7 bytes
However, because the bit-wise operators have operator precedence over the logical checks, you can combine both to save a byte here:
A|B&&C // 6 bytes
Use n+=...-n
instead of (long)...
When you have a long as both in and output in a lambda, for example when using Math.pow
, you can save a byte by using n+=...-n
instead of (long)...
.
For example:
n->(long)Math.pow(10,n) // 23 bytes
n->n+=Math.pow(10,n)-n // 22 bytes
This saved a byte in this answer of mine, and even two bytes by combining -n-1
to +~n
in this answer of mine.
package
can be skipped. \$\endgroup\$