Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Are there any useful shortcuts that can be used in Java?

As shown below, import already adds at least 17 characters to a program.

import java.io.*;

I understand that the simple solution would be to use another language, but it seems to be a real challenge to shorten Java programs.


Tips should be specific to Java: if they're applicable to most C-like languages, they belong in the more general list of tips.

share|improve this question
4  
package can be skipped. –  st0le Jul 19 '12 at 7:08
    
In an answer, can't I just omit the imports assuming they are there? –  Fabricio May 8 at 15:24
    
@Fabricio Not unless the OP specifies so. –  nyuszika7h Sep 26 at 18:49

16 Answers 16

  • Use the most recent possible java. Java 8 lets you use lambda expressions, so use it if you need anything even like functional objects.

  • Define shortened functions for things you use a lot. For instance, you have a hundred calls to exampleClassInstance.doSomething(someParameter), define a new function void d(ParameterType p){exampleClassInstance.doSomething(p)} and use it to save yourself some characters.

  • If you are using a particular long class name more than once, like

    MyEventHandlerProxyQueueExecutorServiceCollectionAccessManagerFactory
    

    instead define a new class:

    class X extends MyEventHandlerProxyQueueExecutorServiceCollectionAccessManagerFactory{}
    

    If you are only using one particular method of that class (but still need to instantiate it), you can define a shortened version inside the new class at the same time.

  • Use function type parameters to shorten things, where possible, like this:

    <T>void p(T o){System.out.println(o);}
    
  • Use for(;;) instead of while(true).

  • Do not use access modifiers unless absolutely necessary.

  • Do not use final for anything.

  • Never put a block after a for loop (but a foreach loop for(x:y) is different). Additional statements should be placed inside the for statement itself, like for(int i=0;i<m;a(i),b(++i))c(i);.

  • Use inline assignment, incrementation, instantiation. Use anonymous inline classes where appropriate. Use lambdas instead if possible. Nest function calls. Some functions are guaranteed to return their parent object, these ones are actually even meant to be chained together.

  • Your main method throws Exceptions, not catches them.

  • Error is shorter than Exception. If for some reason you really need to throw messages up the stack, use an Error, even if it is perfectly normal situation.

  • If some condition would require immediate termination, use int a=1/0; rather than throw null; or System.exit(0);. At run time, this throws an ArithmeticException. If you already have a numeric variable in your code, use it instead. (If you already have import static java.lang.System.*;, go with exit(0);.)

  • Instead of implementing interfaces, like List<E>, extend an immediate (or not-so-immediate, if there is any advantage to doing so at all) child class, like AbstractList<E>, which provides default implementations of most of the methods, and requires only the implementation of a few key pieces.

  • Write your code out in longhand first, with newlines, indentation, and full variable names. Once you have working code, then you can shorten names, move declarations around, and add shortcut methods. By writing it out long to start, you give yourself more opportunity to simplify the program as a whole.

  • Compare alternative optimizations to a piece of code, because the most optimal strategy can change dramatically with very small changes to the code. For instance:

    • If you have only up to two calls to Arrays.sort(a), the most efficient way to is to call it with its fully qualified name, java.util.Arrays.sort(a).
    • With three or more calls, it is more efficient to instead add a shortcut method void s(int[]a){java.util.Arrays.sort(a);}. This should still use the fully-qualified name in this case. (If you need more than one overload, you are probably doing it wrong.)
    • However, if your code needs to also copy an array at some point (usually done with a short for loop in golfing, in the absence of an easily-accessible library method), you can take advantage of Arrays.copyOf to do the task. When more than one method is used, and there are 3 or more calls, doing import static java.util.Arrays.*; is the most efficient way of referring to those methods. After that, only if you have more than 8 separate calls to sort should you be using a shortcut method for it, and only at 5 or more calls is a shortcut warranted for copyOf.

    The only real way of performing such analysis on code is to actually perform potential modifications on copies of the code, and then compare the results.

  • Avoid using someTypeValue.toString(); method, instead just append someTypeValue+"".

  • If you do need windows, don't use Swing, use AWT (unless you really need something from Swing). Compare import javax.swing.*; and import java.awt.*;. Additionally, components in Swing have a J prepended to their name (JFrame, JLabel, etc), but components in AWT don't (Frame, Label, etc)

share|improve this answer

With a static import:

import static java.lang.System.out;
// even shorter (thanks to Johannes Kuhn):
import static java.lang.System.*;

you can save some boilerplate later, but you need multiple invocations to reach a payoff:

public static void main (String[] args) {
    out.println ("foo");    
    out.println ("bar");    
    out.println ("baz");    
}
share|improve this answer
4  
:O. You can do this?! And all this time I thought that this was impossible in Java! –  Quincunx Dec 20 '13 at 7:17
5  
you can even use import static java.lang.System.*. –  Johannes Kuhn Dec 20 '13 at 19:16

Rather than using the import static java.lang.System.* technique to save on println() statements, I've found that defining the following method is much more effective at saving characters:

static<T>void p(T p){
    System.out.println(p);
}

This is because it can be invoked as p(myString) rather than out.println(myString) which has a much quicker and more dramatic character payoff.

share|improve this answer

The argument to main doesn't have to be called args, and you can cut some whitespace:

public static void main(String[]a){}

will do just fine.

share|improve this answer

If you are going to be using some method a lot, assign its resident class to a variable. For example, assign System.out to a variable:

java.io.PrintStream o=System.out;
//now I can call o.print() or o.println() to the same effect as System.out.println()

Also for Integer.parseInt():

Integer i=1;
i.parseInt("some string");

This will almost surely trigger an ide warning about "accessing static method from variable"

share|improve this answer

For golfing that doesn't require input, you can use static blocks, and run it just fine without any main method, just compile it with Java 6.

public class StaticExample{
    static {
        //do stuff
    }
}
share|improve this answer
1  
Did you try to compile and run it? This block is run when the class gets loaded by the class loader. But the class loader won't load anything until it knows of a class with a main method. –  Cruncher Dec 20 '13 at 15:31
    
@Cruncher You can get around that by yourself telling java on the command line/in a manifest file which class to load. –  AJMansfield Dec 22 '13 at 1:20
5  
@Cruncher, this worked with Java 6. Java 7 changed the way it works. –  Peter Taylor Dec 31 '13 at 18:36
1  
Throws an exception at the end but it works! Even in Java 7 –  Jop Vernooij Jun 23 at 16:00
1  
@JopVernooij If you don't want to have an exception thrown to your face, you can system.exit(), but you'll waste characters, no golf challenge ever asks you to avoid exceptions ;) –  Fabinout Jul 1 at 8:57

If you ever have to use the boolean expressions true or false, replace them with 1>0 and 1<0 respectively.

For example:

boolean found=false;
for(i=0; i<10; i++) if(a[i]==42) found=true;

This linear search example can be reduced to

boolean f=1<0;
for(i=0;i<10;)if(a[i++]==42)f=1>0;
share|improve this answer
4  
If you're going to need a lot of true/false, just add boolean t=1>0,f=1<0;. Then instead of 1>0, use t and save two chars per use. Payoff over 1>0 method comes at 10 uses. –  Geobits Mar 11 at 2:17
7  
@Geobits: boolean t=1>0,f=!t; - one char shorter! –  bobbel Apr 11 at 14:07
    
The example is not really good. In this case and many(!) others you can avoid using true/false directly anyway: f|=a[i++]==42; saves quite a lot. –  Ingo Bürk Sep 27 at 11:59
    
@IngoBürk True. When I was writing this I was mostly thinking about library functions that uses boolean, but since I couldn't come up with any examples at the time of writing (I don't usually code in Java) I just wrote a simple example. –  ace Sep 30 at 19:17

With varargs you can "cast" a parameter to an array of the same type:

void f(String...x) {
    x = x[0].split("someregex");
    // some code using the array
}

instead of

void f(String s) {
    String[] x = s.split("someregex");
    // some code using the array
}
share|improve this answer

I don't know if you would consider this 'pure' Java, but Processing allows you to create programs with little initial setup (completed automatically).

For console output, you can have something as simple as:

println("hi"); //done

for graphical output, a little more:

void setup() {
  size(640,480);
}
void draw() {
  fill(255,0,0); //color used to fill shapes
  rect(50,50,25,25); //25x25 pixel square at x=50,y=50
}
share|improve this answer
    
+1 Excellent resource! I'll be sure to play around with it. –  mdeitrick Jul 19 '12 at 19:07
    
Would it be alright if I added other people's answers to this one? Or does that defeat the purpose of a community wiki? –  mdeitrick Sep 16 '12 at 13:45
1  
By the way, you do not even have to call size at all; it will default to a 100 by 100 pixel square. In most OSes, the frame around it will be about twice that large, with the square centered and the rest of the area filled with content taken from the desktop. –  AJMansfield Dec 20 '13 at 12:32

If you use enum instead of class, you save one character.

enum NoClass {
    F, G, H;    
    public static void main (String[] args) {

    }
}

But you have to introduce at least one enum instance (F, G, H in this example) which have to payoff themselves.

share|improve this answer
    
Seems you don't need any enum instances. I did enum M{;public static void main(String[]a){...} with no problems. –  Danny Jan 27 at 14:47
1  
@Danny But then it doesn't save any characters. class M{ is exactly the same length as enum M{;. In that case, I'd go with the class because it is prettier (IMO) –  Quincunx Feb 21 at 23:32
    
at least for me enum{ worked without a ; after; its only the IDE moaning that there is a error butthe compiler accepts it –  masterX244 Mar 5 at 22:30
    
@masterX244 What compiler/version? Mine throws a tantrum and won't do it. –  Geobits Apr 16 at 14:04
    
worked on java 1.7 for me (appeared s, ned to investigate further cause with a update to .8 it stopped working) –  masterX244 Apr 16 at 17:41

If you need to grab a number from an argument (or any other string), normally you see something like:

public static void main(String[]a){
    int n=Integer.valueOf(a[0]);
    ...
}

Many times, you don't need an Integer. Plenty of challenges don't use large numbers. Since Short and Byte will both unbox to an int, use the more appropriate valueOf() instead and save a couple bytes.

Keep your actual variable as an int, though, since it's shorter than both byte and short:

int n=Byte.valueOf(a[0]);

If you need to do this for multiple numbers, you can combine with this method:

Byte b=1;
int n=b.valueOf(a[0]),m=b.valueOf(a[1])...
share|improve this answer

Don't use public class. The main method needs to be public, but its class doesn't. This code works:

class S{public static void main(String[]a){System.out.println(System.getProperty("java.version"));}}

You may run java S even though class S is not a public class.

Plenty of Java programmers don't know this! About half the answers to a Stack Overflow question about main in non-public class wrongly claim that the main method must be in a public class. Now you know better. Delete the public in public class and save 7 characters.

share|improve this answer

We all know about the bitwise xor (^), but it is also a logical xor.

So (a||b)&&!(a&&b) simply becomes a^b.

Now we can use xor.

Additionally, the operators | and & also work, just remember that operator precedence changes.

share|improve this answer
2  
As long as you remember precedence, you can use & and | also. It might be useful if your conditions are already in parentheses, or if you're already working with booleans. –  Geobits Apr 16 at 18:23

Don't use Random!

In general, if you need random numbers, Random is a horrible way to go about it*. Much better to use Math.random() instead. To use Random, you need to do this (let's say we need an int):

import java.util.*;
Random r=new Random();
a=r.nextInt(9);
b=r.nextInt(9);

Compare that to:

a=(int)(Math.random()*9);
b=(int)(Math.random()*9);

and:

int r(int m){return(int)(Math.random()*m);}
a=r(9);
b=r(9);

The first method takes 41+15n characters (n is number of calls). The second is 25n characters, and the third is 43+7n.

So, if you only need it once or twice, use the inline Math.random() method. For three or more calls, you'll save by using a function. Either one saves characters on the first use over Random.


If you're already using Math.random() for double, remember that at four uses, it's still a savings to pull it out into:

double r(){return Math.random();}

For 33 characters, you'll save 10 on each call to r()


Update

If you need an integer and want to save on casting, don't cast it! Java auto-casts if you do an operation instead of an assignment. Compare:

a=(int)(Math.random()*9);
a=9;a*=Math.random();

* Unless you have to seed the PRNG for predictable results. Then, I don't see much of a way around it.

share|improve this answer
1  
Don't forget about Random#nextGaussian though. –  Quincunx Apr 18 at 20:37
    
@Quincunx True, doing the math to get a good normal distribution would lose you any savings you got. I'll just refer to that as the exception that proves the rule ;) –  Geobits Apr 18 at 21:47
    
Note that (int)(Math.random()*9) has a very small modulo bias, because Math.random() returns 253 possible values, and 253 is not a multiple of 9. The probability of each number is within 1/9 plus or minus 5/(9*2**53), an error so small, it is almost exactly 1/9. –  kernigh Jun 20 at 16:32
    
@kernigh Right, I was using 9 just as an example, it could be anything. I'm relatively sure that nextInt() (or any other Random method) has a small bias as well, just due to how Java's PRNG works. –  Geobits Jun 20 at 19:59

This may seem obvious, but there are shorter options for some Math functions:

a=Math.max(b,c);
a=b>c?b:c;

a=Math.min(b,c);
a=b<c?b:c;

a=Math.abs(b);
a=b<0?-b:b;

a=Math.round(b);
a=(int)(b+.5);          // watch for precision loss if it matters
share|improve this answer

Using Java Applet can save you a lot of space:

import java.applet.Applet;

public class B extends Applet{
    public B(){
        System.out.print("Hello world!");
    }
}

Output:

Hello world!

Also this can be even more shorten by making be to extends nothing.

public class B{
    public B(){
        System.out.print("Hello world!");
    }
}

How ever in additional to desired output we will also get exception:

Output:

Hello world!
java.lang.ClassCastException: B cannot be cast to java.applet.Applet
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

Also you can combine this with static block and save another 4 bytes like this:

public class B{
    static{
        System.out.println("Hello world!");
    }
}

Same output with exception as above.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.