text:
Tips for golfing in Java

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.

package can be skipped.

In an answer, can't I just omit the imports assuming they are there?

@Fabricio Not unless the OP specifies so.

Best tip about golfing Java: don't use it. ;)

"I want to golf in java" good luck

JAVA 11: make use of the "var" type inference

@BitBeats Java 10, really

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)

Use interface instead of class.
In java 8, static methods were added to interfaces. In interfaces, all methods are public by default. Consequently
class A{public static void main(String[]a){}}

can now be shortened to
interface A{static void main(String[]a){}}

which is obviously shorter.
For example, I used this feature in the Hello, World! challenge.

I didn't know that! +1, nice trick

Yay, less boilerplate!

I have to partially disagree (also, I beat you in the "Hello, World!" challenge, using that technique).

I would use a static initializer...needs no interface, no public and no main...in combination with enum...

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
}

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");
}

:O. You can do this?! And all this time I thought that this was impossible in Java!

you can even use import static java.lang.System.*.

I know this is an old answer, but in Java 10 you can now do var o=System.out; which only needs to be used twice before it pays off

@LukeStevens: Well, maybe you find some other improvements, possible with Java10, and form a separate answer around Java10?

@LukeStevens Would var o=System.out.println work?

@MilkyWay90: I understand it this way:var o=System.out; o.println(foo);o.println(bar);

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.

Do answers need to include the main function if it doesn't explicitly state to write a full program?  I've been using lambda expressions as answers.

@Makotosan No they don't; Lambdas are usually fine.

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;

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: boolean t=1>0,f=!t; - one char shorter!

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.

@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.

@Geobits not too familiar with java but could you just define 1 and use t and !t (again I dont know Java, just curious)

@AlbertRenshaw if you do int t = 1; you'll get error: bad operand type int for unary operator '!'. If you do boolean t = 1; you'll get error: incompatible types: int cannot be converted to boolean

@ace sorry that should have read "Could you just define one*" haha, as in one variable (t or f). My internet slang has ruined me xD

@AlbertRenshaw Well then of course you can. It depends on how many times false has to be used. If you use it, say, only 1 to 2 times, while you use true a lot, then certainly your suggestion would be useful. But not if you need to use it for, say, 100 times.

There are a lot of languages in which you can do this.

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;
(In certain situations, (a|1)%2*a, may be shorter)

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

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"

((Integer)1).parseInt("1") works too.

@carusocomputing new Integer("1") is even shorter. But what Justin meant with his answer is that you can reuse variables you already have for static calls. As I explain at the bottom of this answer.

Maybe in vombination with var...

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.

The usage of to  avoid having to type Object is a really neat touch!

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.

More generally for your last point, you can access/invoke static members from a non-static context such as an instance of the object.

@OlivierGrégoire Doesn't seem to work.. (They are flooring as well.)

I do not understand your ceil tip. Why would you want to ceil positive integers? Also, I am not sure if the ceil implementation works.

I also think your floor tip should say If you are using positive doubles / floats instead of If you are using positive integers, as you do not have to floor integers.

since Java automatically floors on integers; I think the proper term is truncation, not flooring.

Ah, well then nevermind.

Another Palindrome strategy String t="";for(int i=s.length();--i>=0;t+=s.charAt(i));return s.equals(t);

@RobertoGraham Hmm, that's actually shorter. Oh, and you can golf --i>=0 to i-->0 as well. Thanks, will edit it.

@RobertoGraham I actually copied my original code from the wrong challenge.. Just s.equals(new StringBuffer(s).reverse()+"") is enough.

Fun (longer) Java 8 one: s.equals(s.chars().mapToObj(i->""+(char)i).reduce((q,w)->w+q).get())

Could i>0&(i+j&1<1) not be golfed to i>0&&i+j&1<1 (regarding the "Use &1 instead of %2 to get rid of parenthesis" paragraph)?

@JonathanFrech I'm afraid not. In Java it will see the i+j&1<1 part as i+j and 1<1, so it will complain & is a bad binary operator (since i+j is an integer, and 1<1 is a boolean). Here the error on TIO for this particular code snippet. I do now realize my tip is incorrect, because the <1 part doesn't work for that same reason.. >.> My bad, thanks for the indirect correction.

@KevinCruijssen Oh. That then, however, also applies to your original snippet.

@JonathanFrech Should be fixed now. As I mentioned in the edited comment above, thanks for the indirect correction.

@KevinCruijssen Yes, now it looks fixed. Did not properly read your comment, thus the duplication. You could extend the tip by mentioning a similiar approach for all powers-of-two-moduli ((a+b)%(1<<n) <-> a+b&((1<<n)-1)), not exceeding the integer's limit.

Primes: n->{int i=n;for(;n%--i>0;);return i%n<2;} for -1.

@primo Oh nice. But isn't the %n obsolete in this case and it's actually -3? For input n=1 it errors due to a division by zero error (which might not make this approach suitable to use everywhere), but because of that there is no need to use %n, is there?

@KevinCruijssen you're right, it's not necessary.

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("works");}}

You may run java S even though class S is not a public class.  (Update: I was using Java 7 when I wrote this tip.  In Java 8, your main method should be in an interface.  In Java 5 or 6, your main method should be in an enum.)
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.

Unless you are targeting a Java prior to 1.8, the construct interface s{static void main(String[]... is shorter. If you must have a compilable source file and main method. Because in a Java 1.8 interface, all methods are public so you can skip the modifier on the method(s).

I have not recently used Java, so my answer is getting outdated. I forgot that interfaces can have methods in Java 8.

I didn't learn it from programming; I learned it from golfing :)

You don't have to use Character.toLowerCase(char c). Instead use (c|32). Instead of Character.toUpperCase(char c) use (c&95). This only works with ASCII letters.

c|~32 would tend to result in -1... better to use c-32.

@feersum That would not work if you wanted to make an upper case letter upper case.

Late to the party: c&95 for uppercase.

If you need Integer.MAX_VALUE (2147483647), use -1>>>1. Integer.MIN_VALUE (-2147483648) is better written 1<<31.

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])...

int n=new Byte(a[0]); is three shorter. If the number might be larger, use long n=new Long(a[0]), it's still better than ints in most cases.

Convert String to number
There are multiple ways to convert a String to an numeric value:
String s = "12";

ABC.parseABC:
Short.parseShort(s); // 20 bytes
Integer.parseInt(s); // 20 bytes
Long.parseLong(s);   // 18 bytes

ABC.valueOf:
Short.valueOf(s);    // 17 bytes
Integer.valueOf(s);  // 19 bytes
Long.valueOf(s);     // 16 bytes

ABC.decode:
// Note: does not work for numeric values with leading zeros,
// since these will be converted to octal numbers instead
Short.decode(s);     // 16 bytes
Integer.decode(s);   // 18 bytes
Long.decode(s);      // 15 bytes

new ABC:
new Short(s);        // 13 bytes
new Integer(s);      // 15 bytes
new Long(s);         // 12 bytes

So, for code-golfing, it's best to use the constructor when converting a String to a numeric value.
The same applies to Double; Float; and Byte.

This doesn't always apply when you can re-use an already present primitive as object.
As example, let's say we have the following code:
// NOTE: Pretty bad example, because changing the short to int would probably be shorter..
//       but it's just an example to get the point across

short f(short i,String s){
  short r=new Short(s);  // 21 bytes
  ... // Do something with both shorts
}

You can use .decode instead of the shorter constructor by re-using the parameter as object:
short f(Short i,String s){   // Note the short parameter has changed to Short here
  short r=i.decode(s);   // 20 bytes
  ... // Do something with both shorts
}

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
    }
}

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 You can get around that by yourself telling java on the command line/in a manifest file which class to load.

@AJMansfield I'm pretty sure the manifest file is to tell java which class has main. If it doesn't have main in it, it shouldn't load it

@Cruncher, this worked with Java 6. Java 7 changed the way it works.

Throws an exception at the end but it works! Even in Java 7

@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 ;)

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.

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.

If you need a (much) lower precedence, you can use != instead of ^ for xor, and == for xnor

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.

Don't forget about Random#nextGaussian though.

@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 ;)

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 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.

In rare cases its actually better to extend random.

Something related for when you want a random boolean: instead of new java.util.Random().nextBoolean() you can use Math.random()<.5.

Don't be afraid to use scientific notation
If you are dealing with doubles, or floats, you can use scientific notation for numbers. So instead of writing double a=1000 you can change it to double a=1e3 to save 1 byte.

Try using int instead of boolean
In some cases I've found that it's shorter to return an integer value from a method that would normally return a boolean, similarly to what might be done in C programs.
Right off the bat int is 4 bytes shorter than boolean. Each time you write return 0 instead of return 1<0, you save an additional 2 bytes and the same for return 1  over return 1>0.
The pitfall here is that each time you want to use the return value directly as a boolean, it costs 2 bytes (if(p(n)) v. if(p(n)>0)). This can be made up for by use of boolean arithmetic. Given a contrived scenario where you want to write
void a(int[]t){t[0]+=p(n)?10:0;}

you can instead write
void a(int[]t){t[0]+=p(n)*10;}

in order to save 2 bytes.

I do this pretty often when golfing, but keep in mind that the general consensus is that 0 and 1 don't constitute false/true in Java (and the JLS doesn't consider them that way either). So if the golf is specifically asking for truthy/falsy, you need to booleanize it (and, unfortunately, make it a boolean function, throwing even more bytes at it).

t[0]+=p(n):10?0; Is this even valid?

@dorukayhan no, it is meant to be t[0]+=p(n)?10:0;. (I edited it.)

@Geobits has this concensus changed? I was recently advised to use 0/1 for false/true

@simonalexander2005 I've been away for a couple years, so I'm not the best person to answer that. It may be worth bringing up on Meta, or maybe not. If you do it and get downvoted for it, you'll know ;)

@simonalexander2005 for questions asking for true/false the consensus still holds. However, many questions now only require that two distinct values are returned without requiring true or false explicitly

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.

Seems you don't need any enum instances. I did enum M{;public static void main(String[]a){...} with no problems.

@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)

at least for me enum{ worked without a ; after; its only the IDE moaning that there is a error butthe compiler accepts it

@masterX244 What compiler/version? Mine throws a tantrum and won't do it.

worked on java 1.7 for me (appeared s, ned to investigate further cause with a update to .8 it stopped working)

@masterX244 For me, both OpenJDK 6 and 7 refuse to compile with the message <identifier> expected

@14mRh4X0r mystery error that it appeared to work for me, need to dig deeper :(

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
}

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.

For graphical output, if you don't need animation, you can just write everything outside of setup() and draw() to use "static mode". You can also use 6-digit hex colors and the interpreter will change them, which sometimes pays off (#FF8000 < 255,128,0), and if you're using greyscale only one number needs to be specified (255 < 255,255,255)

Shortening returning
You can shorten return statements of strings by a byte with:
return "something";
to
return"something";
And, if you happen to begin your return statement with a parenthesis, you can do the same thing with them:
return (1+taxRate)*value;
to
return(1+taxRate)*value;
I guess quotes are considered like parentheticals? I actually picked this up through AppleScript, funnily enough, and thought it might be worth mentioning.

Same applies to number signs, like return-n; instead of return -n; or return~n; instead of return ~n;. As well as single instead of double quotes: return'A';

Basically, works for anything which can't be part of an identifier (i.e. non-letter and non-digit).

Use Java 10's var
If you define a single variable of a specific type, use var.
Examples
var i=0;                        // int
var l=0L;                       // long
var s="";                       // String
var a=new int[]{1,2,3};         // int[]
var i=java.math.BigInteger.ONE; // BigInteger
var m=new java.util.HashMap();  // HashMap
var i=3+"abc".length()          // int
var a="a b c".split(" ");       // String[]
for(var a:"a b c".split(" "))   // String

Not usable in any of the following examples
var cannot be used in many examples
var i=1,j=2;           // only one variable is accepted at a time
var a={1,2,3};         // arrays must be explicitly declared
var f=a->a+" ";        // can't know what type a is.
var f=String::replace; // method references aren't properly inferred (weirdly, though)

RE why this doesn't work with method references, note that there are standard functional interfaces for only a small set of signatures (and methods can throw checked exceptions).

One relevant StackOverflow post on the topic of var's method reference limitations.

@Jakob Because while they may be "standard', they're not special to the compiler afaik. Suppose you have a method returning a boolean. Should the type be inferred as a Function<T, Boolean> or a Predicate<T>?

Avoid StringBuilders
Appending stuff to a String takes up much fewer bytes.
// s is a StringBuilder
s.append("Hello, World!");

// S is a String
S+="Hello, World!";

If you have to reverse a string and print it right away, use a StringBuffer.
System.out.print(new StringBuilder("Hello, World!").reverse());
System.out.print(new StringBuffer("Hello, World!").reverse()); // Note that you can omit toString() when printing a non-String object

If you have to reverse a string and then do something else than printing it, use a foreach loop.
String b=new StringBuffer("Hello, World!").reverse().toString();
String B="";for(String c:"Hello, World!".split(""))B=c+B;

A foreach loop is shorter than StringBufferfor reversing strings. String b="";for(char c:"Hello, World!".toCharArray()){b=c+b;}

You should also remove the {} from that foreach loop if you're going to use that method.

Save 2 bytes using String s:"".split("") instead of char c:"".toCharArray().

If you have java.util.stream.Stream already imported, and if you need to chain another call to the result (like B.chartAt(42)) or if you just need to pass the result to a function (like f(B)), then using for(:) is equall to Stream.of("Hello, World!".split("")).reduce("",(a,b)->b+a).

Both lines in your example with the for-each can be golfed. First one can become: String b=new StringBuffer("Hello, World!").reverse()+""; (.toString replaced with +""), and your second line can become: String B="";for(String c:"Hello, World!".split(""))B=c+B; (char to String and .toCharArray() to .split("")).

Hmm, you can replace .toString() with +"" in your last example, so using StringBuffer#reverse is actually 1 byte shorter than the for-each loop..

Use new Stack() when you need basic List functionality
When you need a java.util.List (for example when you want to .add(Object), .remove(Object), java.util.Collections.shuffle(java.util.Collection), etc.), I used to use java.util.ArrayList in most of my answers. But I was recently tipped to use java.util.Vector instead, and java.util.Stack is even shorter:
import java.util.*;

List a=new ArrayList();   // 23 bytes
List b=new Vector();      // 20 bytes
List c=new Stack();       // 19 bytes

Shortest full program templates.
Introduction
The Java spec never ever say that a full program must contain a main method. It only says:

The Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings.

So to the best of our efforts, we can define a Java program as something which when invoked in this way will provide an output:
$ javac A.java
$ java A

All the following templates do that.
Java 8 (42 bytes)
interface A{static void main(String[]a){/* Your code here */}}

Java 7 (45 bytes)
class A{public static void main(String[]a){/* Your code here */}}

Java 5, 6 (12 or 27 bytes)
enum A{A;{/* Your code here */}}

This code above will write something on stderr. Usually something like java.lang.NoSuchMethodError: main\nException in thread "main". If you can write on stderr after execution, use this!
enum A{A;{/* Your code here */System.exit(0);}}

This code above is longer (27 bytes), but it will execute your code and avoid writing anything on stderr.
Conclusion

Don't ever use Java 7.
If your program can be written in Java 5 or 6, use it. If your program can be written in Java 5 or 6, but is longer than a Java 8 version, always check if it could be shorter to write it in Java 5 or 6.

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 B 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 constructor block and save another 10 bytes like this:
public class B{
    {
        System.out.println("Hello world!");
    }
}

Same output with exception as above.

One could argue that in case of an applet the HTML page in which it is embedded should count too.

@PaŭloEbermann  Html page is the output of the program, here we are talking about the source code

Did applets change so much since I used them 20 years ago? Back then, you had a HTML document with an <applet class=...>...</applet> in it, which, when opened in a web browser, would execute the applet. The result of your System.out could appear in a Java console, but not in the HTML page itself. (You could some APIs to execute Javascript in the browser, thereby changing the page, but that is not what you are showing here.)

@PaŭloEbermann Well you said it, this is definitely not the intended way of using applets, but if it's sufficient for your program to print to stdin and it can ignore the stderr than you can use my suggestion. Obviously, it will not print anything to a web page.

When you have a method that should return a boolean or Boolean, i.e.:
// Return true if the (non-negative) input is dividable by 5
boolean c(int i){return i%5<1;}

You can change the boolean/Boolean return-type to Object to save 1 byte:
Object c(int i){return i%5<1;}

In addition, as you may have noticed, you can use a <1 check instead of ==0 to save a byte. Although that is more a general code-golf tip instead of Java-specific.
This is mostly used when the integer can't be negative, like checking for length:
a.length<1

instead of
a.length==0

Nice tip! You may want to add another example in the "if it can't be negative" section to illustrate it, since c(-21) returns true with the current one.

Clarified. Also, don't you mean c(-20) instead of -21? -21 % 5 = 4 and -20 % 5 = 0.

No, I meant -21. -21 % 5 != 4 in Java, which is my point. The divisible by five function would work correctly if modulus always returned non-negative, but it doesn't. See this example snippet.

@Geobits Ah, thanks for the example. I almost never use negative numbers with %, so I forgot Java returns the remainder instead of the modulus, hence the difference..

How to Draw in Java...
Here's the shortest possible GUI paint boiler-plate:
import java.awt.*;
static void main(String[]x){
    new Frame(){
        public void paint(Graphics g){
            // Draw your stuff here.
        }
    }.show();
}

Golfed for 111 Bytes:
import java.awt.*;static void main(String[]x){new Frame(){public void paint(Graphics g){/*CodeHere*/}}.show();}

In most cases, your program will be single-threaded, i.e it'll have only one thread running. You can exploit this fact by returning from the main method when you have to exit instantly.
static void main(String[]a){if(condition)return;}

Compare it to "properly" terminating the program:
static void main(String[]a){if(condition)System.exit(0);}

Or pointing to null:
static void main(String[]a){if(condition)throw null;}

Or dividing by 0:
static void main(String[]a){if(condition)int A=1/0;}

Using ... (varags) as parameter
In some cases it's shorter to use a Java varargs as parameter instead of loose ones.
For example:
// Example input/output: 5, 4, 3 -> 60000
int calculateVolumeInLiters(int width, int height, int depth){
  return width * height * depth * 1000;
}

Would be golfed by most to this:
int c(int w,int h,int d){return w*h*d*1000;} // 44 bytes

But can be golfed an additional byte to this:
int c(int...a){return a[0]*a[1]*a[2]*1000;}  // 43 bytes

Note that all three integers are only accessed once in the method itself. Since int is pretty short it is only beneficial if you use them each only once inside the method, and have three or more of them as parameter.
With longer parameters this is usually more useful though. For example, this was my original answer for this challenge (calculate occurances of input character in input string):
// Example input/output: tttggloyoi, t -> 3

int c(String a,char b){return a.replaceAll("[^"+b+"]","").length();} // 68 bytes

And I was recommended to golf it to this:
int c(String a,char b){return a.split(b+"").length-1;}               // 54 bytes

But I ended up golfing it to this using ...:
int c(String...a){return a[0].split(a[1]).length-1;}                 // 52 bytes

NOTE: If the question/challenge asks for a flexible input, the ... can be shortened to [] of course. If the question/challenge specifically asks for, let's say, three String inputs and disallows an String-array containing three values, you can use String... instead of String a,String b,String c.

Can't you use a String[] instead of using varargs? (saves 1 more byte)

@KritixiLithos Hmm.. good point. But that mainly depends on how flexible the input is for the challenge. If any input format is allowed, than that would indeed be shorter. I'll add this to this tips, thanks.

Sometimes, a single for-loop statement might be replaceable. Consider the following code:
int m(int x){int i=1;for(;x%++i==0;);return i;}

This is a simple for-loop which is a solution to this question.
Since we know that i will not be large enough to cause StackOverflow errors, we can replace the for-loop with recursion instead:
int m(int x,int i){return x%++i>0?i:m(x,i);}

We can simulate a loop by using a ternary operator in the return statement to cause recursion.
This reduction is rather specific, but I can imagine more situations where this would come in handy.

If you use Java 8, then you can:
Replace Lambda expressions with method references
Lambda expressions can be replaced with method references. Method reference has following form:
ClassName::methodName

so if you use one letter names for classes it's shorter then lambda. Here are the rules
lambda form                  |  reference method form
-------------------------------------------------------------------------------------------------
p -> ClassName.methodName(p) |  ClassName::methodName
p -> new ClassName(p)        |  ClassName::new
p -> p.methodName()          |  ClassName::methodName // where ClassName is class of object p
(p, q) -> p.methodName(q)    |  ClassName::methodName // where ClassName is class of object p

Examples (respectivly):
lambda                       |  reference method
-------------------------------------------------------------------------------------------------
p -> System.out.println(p)   |  System.out::println
p -> new HashSet<>(p)        |  HashSet::new
p -> p.getName()             |  Beer::getName
(p, q) -> p.compareTo(q)     |  String::compareTo

So, if ClassName is "C", then we have following length diffs:
lambda form                  |  reference method form | length diff
-----------------------------------------------------------------------
p->C.methodName(p)           |  C::methodName         | 5 bytes
p->new C(p)                  |  C::new                | 5 bytes
p->p.methodName()            |  C::methodName         | 4 bytes
(p,q)->p.methodName(q)       |  C::methodName         | 9 bytes

Simplify lambda expressions
And here are some rules of simplifying lambda expressions.
General form of lambda expression is
(parameters) -> { statements;}  // (String a, String b) -> {return a.compareTo(b);}

When there is only one expresion, it can be simplified as follows (return should me ommitted):
(parameters) -> expression      // (String a, String b) -> a.compareTo(b)

When type declaration can be ommited, it can be simplified as follows:
(parameters) -> expression      // (a, b) -> a.compareTo(b)

When there is only one parameter and there is no need to declare type, it can be simplified as follows:
parameter -> expression         // (String s) -> System.out.printout(s)
                                // to
                                // s -> System.out.println(s)

Use String#isEmpty()
To check if a String is empty, you could use either of these:
s.length()<1  // 12 bytes
s.equals("")  // 12 bytes

However, using .isEmpty() is one byte shorter:
s.isEmpty()   // 11 bytes

Note that for Lists it's still shorter to check the size instead of using isEmpty():
l.size()<1    // 10 bytes
l.isEmpty()   // 11 bytes

I don't really know Java that well but can't you just use s==""

@JohanduToit In Java unfortunately not. String is an Object, and since Java is passed-by-reference, s and "" doesn't point to the same reference, even if they have the same value. So new String("test") == "test" returns false, and new String("test").equals("test") returns true. String literals are an exception to this rule, so "test" == "test" will return true, because the compiler references to the same spot in the background. Perhaps better explained here or .equals in general here

@JohanduToit You could do s.intern()=="" to force Java to replace it with the equivalent object from the string pool, but that's 14 bytes, not really an improvement over the other methods.

@KevinCruijssen [...] since Java is passed-by-reference [...] -- more importantly since Java does not allow operator overloading and defines equality as identity.

actually, interesting enough, you can use s=="" if you make s="' at first, see my fizz buzz java program for an example https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz/218270#218270  I love how my ide says that s=="" doesn't work, but I can run the program just fine

Bit twiddling actions
Swap variables
You might want to swap int and long variables. The usual way is to have a temporary variable:
void swap(int a, int b) {
  int t=a;a=b;b=t;     //  16 bytes
  System.out.printf("a=%d, b=%d%n", a, b);
}

But you can shorten it like this:
void swap(int a, int b) {
  a^=b^(b=a);          // 11 bytes
  System.out.printf("a=%d, b=%d%n", a, b);
}

Even if you reuse a temporary variable, it's just shorter to write that code, no matter the length of each variable name.
Does work with short and byte but at the cost of casting.
Swap the variables so that the min is in a specific variable and the max is in the other
You have a and b and you don't know which is greater. But you want a to contain the lowest and b to contain the greatest.
void swapMinMax(int a, int b) {
  a^=b<a?b^(b=a):0;            // 17 bytes
  System.out.printf("a=%d, b=%d%n", a, b);
}

Sometimes, you can use lambdas with iterators:
// SUBOPTIMAL: Don't use lambdas here!
Iterator<A>i=a.iterator();for(A x:(Iterable<A>)()->i){if(x==y)break;}return i.hasNext()?i.next():null;
Iterator<A>i=a.iterator();for(;i.hasNext();){if(i.next()==y)break;}return i.hasNext()?i.next():null;
Iterator<A>i=a.iterator();while(i.hasNext()){if(i.next()==y)break;}return i.hasNext()?i.next():null;

// Lambdas save 11 bytes here!
Iterator<A>i=a.iterator();Iterable<A>j=()->i;for(A x:j){if(x==y)break;}for(A x:j){if(x==z)break;}return i.hasNext()?i.next():null;
Iterator<A>i=a.iterator();for(;i.hasNext();){if(i.next()==y)break;}for(;i.hasNext();){if(i.next()==z)break;}return i.hasNext()?i.next():null;
Iterator<A>i=a.iterator();while(i.hasNext()){if(i.next()==y)break;}while(i.hasNext()){if(i.next()==z)break;}return i.hasNext()?i.next():null;

Use Try it online to share lambdas
If the solution can be writen in a lambda, Try it online can help you format and reduce what characters need to be included in the solution.
See this for an example.

Convert number to string
It may seem obvious, you can shorten your code by adding the number to "":
// int a = 123
Integer.toString(a) // 0
String.valueOf(a)   // -2 chars
"".valueOf(a)       // -6 chars
(""+a)              // -13 chars

authors: Tĥêt Pĥŭü Wãî


text:
Generate Friedman numbers
A Friedman number is a number that can be expressed by applying basic mathematical operations(^,/,*,+,-) to all it's digits. The operations need not be applied to each individual digit, but all the digits must be involved. That is, 121= 11^2 --> all digits are involved, but 1 & 1 have been clubbed together to make 11.
Use of parenthesis is allowed, but the trivial solution x= (x) is not a valid solution. Also not valid, x= +x.
Examples

25= 5^2
121= 11^2
343= (3+4)^3
2048 = (8^4)/2+0

Write a program that will take positive two integers and print the number of Friedman numbers in that range(inclusive), and the numbers with the expressions in subsequent lines.
Input -
n m    | n, m integers, n>=0, m>n

Output -
count    | number of Friedman numbers in the given range
fn1 exp1 | Friedman number, expression
fn2 exp2
fn3 exp3
.
.
.

Shortest code posted by Sunday 29th July 00:00 Hrs GMT will be the winner.

Can you add some example Friedman numbers and explain how / works? For instance what is 1/3?

The number is expressed by applying the operations to all it's digits. i.e 25 = 5^2, 126= 6*21, 343= (3+4)^3 and so on

Do you allow unary minus? e.g -5?

@JPvdMerwe check the input specification, you wouldn't need to do that, but if you want to, knock yourself out. Though unary plus is not allowed. i.e +5 is not a valid solution

You haven't answered JPvdMerwe's question about division. Must it be exact? Can intermediate results be non-integral?

As long as the result expression to the original number, it is fine.

Can the number of Friedman numbers found be printed after expression list in output? It will save me 10 chars.

@ArtemIce erm, yeah. That should be alright.

Ruby, 456 438 408 390 370 349 344 334 bytes
g={}
f=->a,b{a.permutation(b).to_a.uniq.flatten.each_slice b}
F,T=$*
([F.to_i,10].max..T.to_i).map{|c|f[a="#{c}".split(''),v=a.size].map{|m|f[[?+,?-,?*,?/,'','**'],v-1].map{|w|(d=(s=m.zip(w)*'').size)==v&&next
0.upto(d){|y|y.upto(d+1){|u|begin(r=eval t="#{s}".insert(y,?().insert(u,?)))==c&&g[r]=t
rescue Exception
end}}}}}
p g.size,g

Output:
% ruby ./friedman-numbers.rb 1 300
9
{25=>"(5)**2", 121=>"(11)**2", 125=>"5**(2+1)", 126=>"(6)*21", 127=>"(2)**7-1", 128=>"2**(8-1)", 153=>"(3)*51", 216=>"6**(1+2)", 289=>"(9+8)**2"}

Also it works relatively fast for larger numbers:
% time ruby friedman-numbers.rb 3863 3864
1
{3864=>"(6**4-8)*3"}
ruby friedman-numbers.rb 3863 3864  14.05s user 0.17s system 99% cpu 14.224 total

I ran it with the input 5 40 and got the result: [11, "11**1", 21, "21**1", 31, "31**1", 41, "41**1"]. No sign of 25 in there and I think the right solution (for example for 21) is 2*1, not 21**1

@w0lf Thank you! I think I've fixed it.

Yes, it works great now.

@w0lf added a lot of characters to format output as required

you can gain 2 chars by replacing '+-*/'.chars.to_a+['','**'] with ["+","-","*","/","","**"]

and one more by using "+^-^*^/^^**".split('^') :-)

@w0lf Yes, thanks. Already got it and replaced with [?+,?-,?*,?/,'','**']

I'm wondering can your code solve 2592 = (25) * (92)? Basically can it do stuff in the form ((a?b)?(c?d)), where a,b,c,d are digits and ? represents an arbitrary expression. As handling that case is what makes my code slow and I'm curious how you do it efficiently. (I really should learn to read ruby)

Just checked and yours doesn't find 2592.

@JPvdMerwe Correct. I will rethink the logic.

Python 2.7 - 380 378 372 371 367 363 357 354 352 348 336 chars
Just a simple brute force search.
from itertools import*
s=lambda x:[x]['1'>x>'0':]+['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]
def E(e):
 try:return eval(e.replace("^","**"))
 except:0
A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}
print len(A)
for v in A:print v,A[v]

Example run:
1
300
9
128 (2^(8-1))
289 ((9+8)^2)
216 (6^(1+2))
121 (11^2)
153 (3*51)
25 (5^2)
125 (5^(2+1))
126 (6*21)
127 ((2^7)-1)

Explanation:
s(x)
is a function that takes a string containing a sequence of digits and returns all expressions using those digits in that order.
[x]['1'>x>'0':]
evaluates to a list containing x if x is '0' or a sequence of digits not starting with '0'; otherwise, it evaluates to an empty list. Basically this handles the case where I join all the digits together.
['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]
basically partitions x into two parts (both being of non-zero length), calls s() on each part and joins all the results together with some operator between them, by using product().
E(e)
is basically a safe eval. It returns the value of e if e is valid and None otherwise.
A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}

Basically this code tries all the numbers in the range, permutes their digits and tests each expression s() generates for that permutation, ignoring the first expression if x doesn't start with '0', because if x doesn't start with '0' then the first expression will just be x.
Alternate version - 397 chars
Here is my code if you are required to use fractions:
from fractions import*
from itertools import*
s=lambda x:["Fraction(%s)"%x]['1'>x>'0':]+['(%s%s%s)'%f for i in range(1,len(x))for f in product(s(x[:i]),'*/-+^',s(x[i:]))]
def E(e):
 try:return eval(e.replace("^","**"))
 except:0
A={i:e for i in range(input(),input()+1)for x in permutations(`i`)for e in s("".join(x))[x>='1':]if E(e)==i}
print len(A)
for v in A:print v,A[v].replace("Fraction","")

I don't think if len(x)<2 will ever be true in function s. Also, you can replace your format with "a[Fraction(%s)%s%s]='(%s%s%s)'"%(x[:i],o,v,x[:i],o,A) to save 4 characters.

@beary605: It is true sometimes, when i=len(x)-1, then the next call will get a single char. As for the second point, thanks! :)

huh... except:0 smart.. very smart. I'll remember

Please include some illustrative output.

@DavidCarraher: Done.

Does it work for 4 digits numbers, let's say range of 3863 to 3864?

@ArtemIce: It should, recursing on both x[i:] and x[:i] makes sure it should work. Problem is it's really slow, I've been running it for a while now and it still hasn't returned.

Nope, still running. I have to move my PC now, but I will let it run for a few days and see if it finishes.

So I gave up on it after leaving it running for almost 20 hours (and using 1.3 gigs of RAM when I stopped it). I do however believe it would work given enough time and memory.

Python3 (436) (434) (443)
It was hard. I can spare some characters if I make output more native.
from itertools import*
r={};k=product;m=map
q=lambda n,h=1:["("+i+c+j+")"for(i,j),c in k(chain(*[k(*m(q,f))for f in sum(([(x[:q],x[q:])for q in range(1,len(x))]for x in m("".join,permutations(n))),[])]),list("+-*/^")+[""]*h)]if 1<len(n)else[n]*h
a,b=m(int,m(input,"nm"))
for i,j in chain(*[k(q(str(n),0),[n])for n in range(a,b+1)]):
    try:exec("if eval(%r)==j:r[j]=i"%i.replace("^","**"))
    except:0
print(len(r))
for j,i in r.items():print(i,j)

Output
n100
m200
6
(2^(8-1)) 128
(3*(51)) 153
((11)^2) 121
(5^(1+2)) 125
(6*(21)) 126
((2^7)-1) 127

So you have a lot of clever tricks; however, I should mention you don't handle 1 to 9 correctly and your input isn't inclusive. You can remove 2 chars though by removing the space after "("+i+c+j+")" and replacing len(n)>1 by 1<len(n) after which you can remove the space after that expression.

Fair. Fixed all, +7 characters

You can replace the last line by for j in r:print(r[j],j) to save 7 chars.

Mathematica 456 416 402 404 400 396 chars
<< Combinatorica`; l = Length; p = Permutations; f = Flatten; c = Cases;
u[d_, o_, s_] :=
 Fold[#2[[1]] @@ If[s == 1, {#1, #2[[-1]]}, {#2[[-1]], #1}] &,
 d[[1]], Thread@{o, Rest@d}];
q[t_, r_] := {u[t, #, r], u[HoldForm /@ t, #, r]} & /@
p[{Plus, Subtract, Times, Divide, Power}, {l@t - 1}];
v[m_, n_] := (t = Table[Union@
  c[f[{#~q~1, #~q~0} & /@
     f[p /@ c[
        FromDigits /@ # & /@
         f[SetPartitions /@ p@IntegerDigits@j, 1], x_ /; l@x > 1],
       1], 2], {j, _}], {j, m, n}]~f~1; {l@t}~Join~t)

Example:
v[1,300]//TableForm

Output:

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Generate ASCII wilderness map
Generate an ASCII wilderness map.
Example output:
................^^^^
..................^^
...^^^^........o....
.....^^^^...........
....................
........o....TT.....
..TTTT..............
TTTT.TTTT....~~~~~~.
..TT..........~~~~~~
....................

Anti-example (don't do this):
....................
...........T........
...^..........oo....
......^.............
....................
..............TT....
T.T.T.T.T........T..
.................T..
T.T.T.T.T..........T
..............TT...T

Rules:

Must be at least 20x10 characters in size
Must be different each run, i.e. random
Must contain continuous and varying shape areas of trees 'T', hills '^' and water '~', most of which should consist of more than 5 cells
The default, ground character is '.'
Must contain at least 2 villages 'o' that are usually not next to each other
Must not contain obvious patterns, such as rectangles or evenly spaced areas - "natural look" is the key
You don't need to explicitly check that the rules are followed (e.g. no need for anti-rectangle logic), but the great majority of the runs (say, 80%) must produce conforming results
With your submission, include an example output

Scoring:
Winner has lowest score from formula: code character count - votes

You mention "conforming results" and "the rules [being] followed", but don't explain what that means, exactly. What are those rules to conform to, and what, exactly, is wrong with your second example?

APL (99 76)
F←⍳S←10 20⋄'.T^~^To'[⊃7⌊1++/(⊂7×F∊{?S}¨⍳2),T×{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳3]

A bit longer than it needs to be (so that it gives better output) but I'll shorten it when the Golfscript answer comes in.

The GolfScript answer was posted so here's a shorter one. I thought of another (rather obvious, in hindsight) way to shorten it so that the output is not much worse than the original program, and it's even shorter than my original backup plan.
(In the old version, I had five bitfields that I was xor-ing with each other, now I have three that I am adding to each other.)
I have replaced the example output with output of the new version, of course.
Explanation:

F←⍳S←10 20: size is 20x10, F is a matrix where each element is its coordinates
{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳5: generate 3 bitfields, by starting at a random coordinate, and taking 99 random steps to a neighbouring field and then setting that bit on. 99 seems high but it often backtracks as it is random. This makes the maps for the areas.
(⊂7×F∊{?S}¨⍳2): Add in two villages.
⊃7⌊1++/: sum the areas, giving a matrix where each number represents a certain type. Cap it at 7, because the villages might appear in another area giving high numbers.
'.T^~^To'[...]: replace each number with the right character. There are 3 possibly overlapping fields so the highest possible value is 6. (3+3)

Example output:
....TTT.TTT...TTT.^^
...TT....TTT....T..^
....T....TT.......^^
...~..o..T..^^...^^.
...~.........^^^^^^^
...~~~~....^^..^^^..
~..~~~......^.^.^^^^
~~.~~~......^^.^^^..
~.~~~~........o.....
~~~~~~..............

and
.....o........~~..~~
..............~~~~~.
.^T.T..........~~.~.
^T~~TTTTTT.......~~~
~~~~TT.TT.T......~~~
^~^TTT....T.....~~~~
^^^^T.....T...T..~~.
^^^^.......TT.T.....
^^^^.........TT.....
^^^^.........o......

Old version:
F←⍳S←10 20⋄G←{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳5⋄'.T^~^To'[⊃7⌊1++/(⊂7×F∊{?S}¨⍳2),T×{(⊃⍵⌽G)∧~⊃∨/1↓⍵⌽G}¨T]

The output is almost exactly how I imagined the best possible result would be like!

JavaScript - 294 290 characters
To encourage attempts, I took a crack at this myself. You can try a live demo here (you need to open your browser's JS console). Tested with Chrome and IE8.
R=function(a){return Math.random()*a|0};t=["~","T"];t.splice(R(3),0,"^");p=["XXX..","XXXX.","XXXXX"];b="....................";for(i=j=0;10>i;++i)j=i%3?j:R(15),s=b.substr(0,i%3?j+R(2):20),s+=p[R(3)].replace(/X/g,t[i/3|0])+b,k=R(19),console.log(s.substr(0,k)+".o"[i%2*R(2)]+s.substr(k,19-k));

Example output:
....................
.......~~~..........
........~~~~~.......
...o................
...............TT.TT
..........o....TTTTT
....................
.....^^^.o..........
.....^^^^^..........
..................o.

It's not ideal, as there is always only three areas (one of each kind), their maximum size is 5x2 cells and after a few runs, you start to notice limitations in their (and villages') placement. However, it fulfills the rules.

GolfScript, 97 characters
"T~^o"1/{:z{[20:s.*:<rand{.[s~)1-1s]4rand=+}z"o"=!9**]}3*++}%2/:x;<,{"."x{)3$\?)!!*+}/\;-1=}%s/n*

Example outputs:
.............~......
...........~.~~.....
........~~~~~~......
........~~~.........
.......~~~..........
.......~............
..^^..............T.
^^^^...........o..T.
...^....TTT...^...T^
^........TT.o.^^^.^^
^.......TT.....^^.T.
........T......^.TT.
................TT..
....................
....~~~.............
....~.~.............
..~o~...............
..~.....TTTT........
.......TT..TT.......
....................

and
.............~......
.............~......
....TTT.....~~TT....
....T.T.....~~TT....
....TT......~~~TT...
.....T.....~~~~T....
.......^^.~~~~......
......^^^..~~.......
......^.^...........
....................
..^^^^..............
..^..^^.............
....^^^^^...........
.......o........TT..
................TT..
....................
......o.............
.............o......
....................
....................

Ruby 1.9 (127 116 112 107)
m=?.*o=W=200
29.times{|i|o+=i%9-i/28>0?[-1,1,20].sample: rand(W);m[o%W]='T~^'[i/9]||?o}
puts m.scan /.{20}/

The output is a bit plain, but I think it mostly meets the spec!
Some example outputs:
....................
........TTTTTTT.....
........T^^^........
.........^..........
.........^..........
.........^^^.o......
....................
.....~.o............
...~~~..............
...~~~~~............

Another:
.....^^.............
......^^............
.......^^...........
...........o........
....................
..............T~~~..
.............TT~~...
.............T.~....
.............T.~....
.o..^^.......TT~....

And again:
.....TT.............
..............~.....
..............~.....
..............~~....
..............~~~...
........^^^.........
....o.T...^.........
......TT..^^^.......
..o..TT....^^.......
.....T..............

Due to the way it's coded, there's almost always a lone tree. I like to imagine it's the Deku tree.

Q (116 107 char)
Here's one in Q
(-1')20 cut@[199{.[t!`s#'(0 20 20 20;0 0 20 20;0 0 0 20;0 1 2 3)!\:t:"T^~.";(x;rand 30)]}\".";2?200;:;"o"];

Sample output
...........o........
...~~....TTTT..~~o..
......TTTTTTTTT....T
T...................
......^^^........TTT
...~~~~.............
....................
............^^......
..~~~..^^^^^^.......
....~..............T

and
..........^^^..^...o
....................
........^.T.........
.......~~...^.......
....................
....TTTTTTTT....^...
..~.................
.o.....^^^^^.......T
............~~~~~~~~
~~~~~....TTT........

and
....................
...~~~~~~~~~~.....~.
................TT..
....TTTTT..~.TT.TTTT
T................TTT
TTT..........TTTTTTT
TTT....T............
........T.......TToT
TTT..............^^.
...TTT..^.~~~~.o....

I can tweak the stochastic matrix to affect the output but I think the above conforms what you're looking for.
/edit: tweaked output
/edit: reduced char count by only adding 2 villages

It violates rule 3: Must contain continuous and varying shape areas of trees 'T', hills '^' and water '~', most of which should consist of more than 5 cells - most of your areas are of size 1.

I'm terrible for reading rules...I've tweaked the distribution, I think it's more conformant now.

Aesthetically some of them are bit too noisy for my taste (too many one character areas), but it follows the rules now (I didn't really do counting, but visually it's close enough), is definitely more random than my solution, very compact etc. Well done!

K, 84
f:{,/{x+!y}'[5?200;5?10]};m::200#".";{@[`m;x;:;y]}'[(f`;f`;f`;2?200);"~T^o"];10 20#m

Output:
"...................T"
"TTTTT~....TTT...^^^."
"...................^"
"^^..............^^^^"
"^^^..~~~~.......^^o."
".........TTTTT......"
"..~~~~~~........TTTT"
"TTT.~..............."
".........o.....^^^^."
"..........TTTTT....."

and
"...............~~~.."
".......~~~~~......TT"
"TTTT.^^^^^^^^......."
"....TT......~~......"
"..........^........."
"...........oTTT..^^^"
"^^^^^^..........^^^^"
"^^...TTTTTTT........"
"................o.~~"
"~~~.............T..."

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
The smallest self-improving program
The goal is to write a program that learns from its own mistakes, and improves itself based on it. This means, that later attempts at the problem should be either faster or more accurate, than earlier ones.
To deny trivial solutions, here is a set of rules (they are rather obvious):

you can choose the problem to be solved, but your choice will be voted upon.
the program should read input, this means the problem must have input variables, and its output should depend on that input.
later runs of the algorithm should be better (at least after a certain number of runs) than the previous ones. Better can mean faster, or more optimal, or more accurate.
the improvement must be real, and not just the disabling of purposefully introduced inhibitors like if (never_run_before()) sleep(100);
the improvement must be caused by your program, and not external factors (like the OS giving faster access to a resource, if it was already opened or more often accessed before)
the iterations can be either successive runs of the program while you save knowledge to a non-volatile storage, or you can have an interactive program which reads input again and again for successive runs of the algorithm.
there should be improvement besides the situation where the algorithm runs faster given the exact same input data. (just storing previous results and doing nothing else would be too cheap). This means, there should be some improvement even if there is no repetition in the input data, for example if the task is to solve a maze, the input maze might be different each time.
the algorithm must be part of your program, so the use of existing machine-learning tools is not allowed (otherwise it would be a too easy win for Matlab and its built-in neural network)

The score is: number of characters - 5 * score form votes. It can be negative. Smallest wins. Winner will be selected not sooner than 10 days after the first valid solution, and has to have a positive vote score.
For voters: the golfing is already an independent part of the score, so pleas don't vote based on the amount of golfing, but on the cleverness of the solution and the hardness and originality of the chosen problem (a program playing a game against the user should worth more than a program calculating the digits of pi)

I think the task is way too unspecified. There is no basis to judge an attempt with respect to size (which is what [tag:code-golf] is about). And since you can only up- or downvote you cannot effectively score distinct answers.

The task may be unspecified, deliberately, but the scoring is unambiguous. You might suggest a more limiting factor for the task if you wish, before the first solution is posted. I wanted to give the solvers some freedom, as in a number of other open-ended quests, like this one: http://codegolf.stackexchange.com/questions/2922/generate-a-random-program-in-your-favorite-language?rq=1 It was not stated what the program must do.

GNU Octave / MATLAB, 14
f=@(n)n+sin(n)

You don't generally take a standard input with Octave programs, so this is a function which gives an improved estimate of pi after every call on its previous output. Sample run:
octave> f=@(n)n+sin(n);
octave> format 'long'
octave> n = 1;
octave> n = f(n)
n =  1.84147098480790
octave> n = f(n)
n =  2.80506170934973
octave> n = f(n)
n =  3.13527633289972
octave> n = f(n)
n =  3.14159261159065
octave> n = f(n)
n =  3.14159265358979

Python, 12
This program golfs itself, improving its own score for this challenge.  It takes two iterations to fully optimize itself.
initial program
print'print'

first output / second program
print

second output / third program: newline
third output / fourth program: empty
all subsequent programs: empty

Quite a cheeky one, I like it. But doesn't it fall foul of the "program should read input" rule?

@Griffin, you're right... dang


text:
Score a game of Go
Scoring a Go game is a task that is not all too easy. In the past there have been several debates about how to design rules to cover all the strange corner cases that may occur. Luckily, in this task you don't have to do complicated stuff like life and death or seki detection. In this task, you have to implement a program that scores a game according to the Tromp-Taylor rules without Komi.
The scoring procedure is pretty simple:

a point P, not colored C, is said to reach C, if there is a path of (vertically or horizontally) adjacent points of P's color from P to a point of color C.
A player's score is the number of points of her color, plus the number of empty points that reach only her color.

For example, consider the following board. X, O and - denote black, white and uncoloured intersections:
- - - X - O - - -
- - - X - O - - -
- - - X - O - - -
- - - X O - - O -
X X X O - O O - -
- - - X O - - O O
- - - X - O - - -
- - - X - O - X -
- - - - - O - - -

Applying the scoring rule yields the following result. x, o and - represent uncoloured intersections that are counted as black, white and nobody's points.
x x x X - O o o o
x x x X - O o o o
x x x X - O o o o
x x x X O o o O o
X X X O o O O o o
- - - X O - - O O
- - - X - O - - -
- - - X - O - X -
- - - - - O - - -

According to the diagram, black has 23 points, white has 29 points of territory. Thus, your program should print W+6 for this board.
I hope it is clear enough this way.
Input and output
The input is a string that contains exactly n² of the characters X, O, - where n is not known at compile time. Your program should ignore all other characters in the input stream. Behavior is undefined if there is no integer n such that the amount of XO- characters equals n². You may assume that n is in [0, 255].
The sequence of characters is to be interpreted as a Go-board of n rows and columns. The output is the absolute value of the difference of the total amount of points of white and black in decimal representation. If white has more points, it is prefixed by W+, if black has more points it is prefixed by B+. In the case that both players have an equal amount of points, the output is Jigo.
Input is to be read in an implementation defined manner. Input may not be part of the source code.
Winning conditions
This is code-golf. Usual code-golf conventions apply. The submission with the least amount of characters in its source wins. Only programs that fully implement the specification may win.
Test cases
Input:
- - - X - O - - -
- - - X - O - - -
- - - X - O - - -
- - - X O - - O -
X X X O - O O - -
- - - X O - - O O
- - - X - O - - -
- - - X - O - X -
- - - - - O - - -

Output: W+6
Input:
Xavier is insane -- says Oliver

Output: Jigo
Inpout:
Code-Golf

Output: Jigo
Input:
-XXXXXXX-XOOOOOOOXXO-OXXXOXXXOX--XOXXOOX
-
XOOXXOX--XOXXXOXXXO-OXXOOOOOOOX-XXXXXXX-

Output: B+21
Input:
- - X O O O O X X - - - - - - X O O -
- X X O X O X X O X X X X X X - X O -
- X O O X X X - O O O X O O X X X O -
- X O O O X X O O O O O O X X X O - -
- - X X O X - X X X X O O O O O O O -
- - X O O X X X - X X X O O O X X O -
- - X O - O X O X O O O O O X X X O -
- X O O - O O O X X X X X O O X O - -
- X X X O - - - O X O X X X O X O - -
X O O O O - - O - O O O O X X X O O -
X X O - - - O - - O O X X - - X X O O
X O O O - - O - O O X - - - - X O O X
- X X X O O X O O X X - - - - X X X X
X - X X X O X X O O X - - X X O X O O
X X O O X O X O X X - - - X O O O O -
X O - O X X X O X - - - - - X O - - -
O O - O X O O O O X X - X X X X O - -
O O - O O O X O X X - - X - X X O - -
- - O - - O X X X - - - - X O O O - -

Output: B+6
More testcases will come soon.
reference implementation
I have created a reference implementation written in ANSI C. This implementation reads input from the standard input and writes output to the standard output.
/* http://codegolf.stackexchange.com/q/6693/134
 * reference implementation
 * by user FUZxxl
 */

#include <stdio.h>
#include <stdlib.h>

#define MAXBOARD 256

/* bit 0x01: black colour
 * bit 0x02: white colour
 * bit 0x04: there is a stone on the intersection
 */

enum colour {
    UNCOLOURED    = 0x0,
    BLACK_REACHED = 0x1,
    WHITE_REACHED = 0x2,
    BOTH_REACHED  = 0x3,
    HAS_STONE     = 0x4,
    BLACK         = 0x5,
    WHITE         = 0x6
};

static enum colour board[MAXBOARD * MAXBOARD] = { 0 };

static int bsize = 0;

static void read_input(void);
static void fill_board(void);
static void show_score(void);

int main()
{
    read_input();
    fill_board();
    show_score();
    return EXIT_SUCCESS;
}

static void read_input(void)
{
    int n = 0;
    int invalue;

    while ((invalue = getchar()) != EOF) {
        switch (invalue) {
            case '-': board[n++] = UNCOLOURED; break;
            case 'X': board[n++] = BLACK; break;
            case 'O': board[n++] = WHITE; break;
        }
    }

    while (bsize * bsize < n) bsize++;

    /* your program may exhibit undefined behaviour if this is true */
    if (bsize * bsize != n) exit(EXIT_FAILURE);
}

static void fill_board(void)
{
    int i,j;
    int changes;
    enum colour here, top, bottom, left, right, accum;

    do {
        changes = 0;

        for (i = 0; i < bsize; ++i) {
            for (j = 0; j < bsize; ++j) {

                here   = board[i * bsize + j];
                if (here >= BOTH_REACHED) continue;

                top    = i == 0 ? UNCOLOURED : board[(i - 1) * bsize + j];
                left   = j == 0 ? UNCOLOURED : board[i * bsize + j - 1];
                bottom = i == bsize-1 ? UNCOLOURED : board[(i + 1) * bsize + j];
                right  = j == bsize-1 ? UNCOLOURED : board[i * bsize + j + 1];

                accum = here | top | bottom | left | right;
                accum &= ~HAS_STONE;

                changes |= board[i * bsize + j] != accum;

                board[i * bsize + j] = accum;

            }
        }

    } while (changes);
}

static void show_score(void) {
    int w = 0, b = 0, n;

    for (n = 0; n < bsize*bsize; ++n) switch (board[n] & ~HAS_STONE) {
        case BLACK_REACHED: ++b; break;
        case WHITE_REACHED: ++w; break;
    }

    if (b != w)
        printf("%s%i\n",b>w?"B+":"W+",abs(b-w));
    else
        printf("Jigo\n");
}

Presumably you mean the last output to be W+7?

No... How do you come to this conclusion?

Er...I assumed that S+ was a typo (because you earlier listed possible output as either W+, B+, or Jigo) and I looked at my keyboard and saw the S is near W... Or do you use Dvorak?

@dmckee I suppose the "S" comes from the german "Schwarz" instead of "Black".

Oh... You're right. Sorry for that

Can you explain the +7 in your last example. My program says +21 - which is also what I get manually according to your rules.

@Howard B has 9, W has 2.  Territory is only counted on the -, so the maximum possible score given the 11 -s in the input would be +11.

@Izkata The rules say we are counting territory including points (see also example given in the text).

My Last example is wrong...  I was pretty tired when I made this post.

So an area is counted as ones' points if it is completely surrounded in ones' markers?

About right. Tromp-Taylor rules don't care about Life and death though.

I'm waiting for an answer in Go...

GolfScript (105 bytes)
{'-XO'?}/]-1-.{2*3%}%{.,:N),{.*N=}?/{{[{.2$+1={+.}*}*]}%zip}N*[]*.1--,\}2*-.{.0>'W+B+'2/=\abs}{;'Jigo'}if

Online demo.
Flood-fill adapted from this earlier answer of mine.
The solution flood-fills one copy of the original board with X, and another with O. Thus empty cells which are reachable by both colours are scored for both, but cancel in the subtraction.

Fair enough. You might win this round.

C (438 434 413 382 364 336 322 298 294 292 290 characters)
#define I b[d*g+e
a;b[65536];c;d;e;f;g;main(){for(;d=getchar()+1;f++)b[f]=d-80?d-89?d-46&&
f--:5:6,g+=g*g<f;while(!c--)for(d=g;d--;)for(e=g;e--;)I]<3?a=3&(I]|!!d*I
-g]|!!e*I-1]|(d<g-1)*I+g]|(e<g-1)*I+1]),c&=I]==a,I]=a:0;while(f--)c+=b[f
]%2-b[f]/2%2;printf(c?"%c+%i":"Jigo",c>0?66:87,abs(c));}

All newlines except the first one inserted for enhanced legibility. A commented and slightly more legible version can be found here.
This answer is essentially the reference solution but with all that useless stuff (such as types [who needs something different from int anyway?] and standards compliance [return value of main? please!])
Corrections and improvements
438 → 434
Dropped explicit initialization of variables after I convinced myself that they are automatically initialized to 0 according to standard.
434 → 413
Removed case statement: If an uncoloured intersection is reachable from both black and white, we can count it as one point for both to simplify the program.
Switch of logical branches to avoid negation.
413 → 382
Assign d to getchar()+1 to save one pair of parenthesis. Under the assumption that b is initialized to zeroes, reorder case statements, discarding all break statements. (a>b?c:0) is longer than (a>b)*c. (d+1)*g+e is longer than d*g+e+g.
382 → 364
Improved looping, no newlines in the output, shorter output routines.
364 → 336
Got rid of that switch statement. (Thanks, Howard!), track difference of points for two characters. Negate c for one character. four characters in the big or clause.
336 → 323
Replacing & by % allows removal of braces for four characters. Fused the square-root with the input loop for nine or so characters (yeah!), removed an if for one char.
323 → 298
Introduced the macro H to replace the often occuring and bulky b[d*g+e] construct.
298 → 294
Change a&=~4 to a&=3 as we only every observe the lowest three bytes of a. Also changed to loop body from ((a=I])<3)?a|=... to I]<3?a=I]|... which is two characters shorter. Also, introduce h instead of reusing c, which is one character shorter.
294 → 292
Eliminate h variable. If we test c with !c-- instead of !c++, c equals 0 at the end of the flood-fill loop and can thus be used for the purpose h was used before (i.e. score keeping).
292 → 290
Replace the construct d-46?f--:0 with d-46&&f-- which is shorter by a character and combine the two assignments to a in the inner loop.

You may replace the switch statement with something like {b[f]=d-80?d-89?d-46?f--:0:5:6;f++;} to save several characters.

@Howard: Yeah. That worked really nice! Thank you

"For enhanced legibility" — as if.

@tomsmeding Well, scrolling one line is much less legible. Also, a commented version is linked to.

@FUZxxl That was meant jokingly. :) Also, you're right in saying it's better than on 1 line.

J (140 136 131 129 119 117 116 characters)
After ramping up my J skills, I can finally provide a submission in J. It's a little bit long though.
exit echo>(*{'Jigo';('B+',":);'W+',":@|)+/,-/1 2=/(]OR(0=[)*[:OR((,.|.)0,i:1)|.!.0])^:_~($~,~@%:@#)3-.~'-XO'i:1!:1]3

The algorithm implemented by this submission is very similar to the reference implementation but different in the way occupied fields are handled.
Here is the solution split up into more parts for easier understandability. The golfed solution is slightly different from that, but the difference isn't very large.
input =. 3 -.~ '-XO' i: 1!:1 ] 3
board =. ($~ ,~@%:@#) input
NB. shift up, down, left, right
rotm =. (,. |.) 0 , i: 1
fill =. ] OR (0 = [) * [: OR rotm |.!.0 ]
filledboard =. fill^:_~ board
score =. +/ , -/ 1 2 =/ filledboard
echo > (* { 'Jigo' ; ('B+' , ":) ; ('W+', ":@|)) score
exit 0

GolfScript, 190 characters
{"XO-"?)},:v,.),\{\.*=}+,~:s.*:`0\,{s%!\2*+}/:r;88{0v@{=\2*+}+/}:%~79%1${{:<.r|r^2*|<2/r|r^|<2s?:h/|<h*|1$|1$^2`?(&}`*}:a~@@a\;.2$|2${^2*)2base{+}*}:m~@2$|@m-.{"BW"1/1$0>="+"@abs}{;"Jigo"}if

The script became much longer than I thought in the beginning. Pass any input on STDIN and the output will then be printed when the program terminates.

Ruby (314)
could be made shorter with some more time:
q={?-=>0,?X=>5,?O=>6};b=[];$<.chars{|c|(t=q[c])&&b<<t}
z=Math.sqrt b.size
loop{c=b.each_with_index.map{|h,i|
next h if h>2
x=i%z
y=i/z
u=y<1?0:b[i-z]
l=x<1?0:b[i-1]
d=y>z-2?0:b[i+z]
r=x>z-2?0:b[i+1]
~4&(h|u|d|l|r)}
break if c==b
b=c}
b.map!{|h|h&~4}
s=b.count(1)-b.count(2)
puts s==0?"Jigo":s>0?"B+#{s}":"W+#{-s}"


text:
It's fun to stay at the Y.M.C.A
"Y.M.C.A." is a popular disco song by the Village People that has a well-known dance. Write the shortest program to output the capital letters "Y", "M", "C", and "A" synchronized to the song's chorus.
Generally, one letter goes on each line sent to standard output. This primarily is to simplify programs subject to the output buffering of the C standard library (printing a newline flushes the output buffer), so you may omit any or all of these newlines if such omission would make your program shorter.
Your program, which is started at the same time as the music, must output the letter "Y" within 0.125 s of each of these times after starting (in seconds; I determined these from the music video posted on YouTube).
 45.766   49.611   60.889
 64.661  109.816  113.591
124.810  128.687  173.830
177.620  188.950  192.724
204.013  207.739  219.057

The letters "M", "C", and "A" respectively come 0.930 s, 1.395 s, and 1.628 s after each "Y". For testing purposes, these relative times are converted into absolute times by adding them to the time of the preceding "Y".
I have written a test program and corresponding example program in C that assume a newline follows each letter (although this is not a rule of competition). It is written for Linux and will not work on Windows without using Cygwin. If you cannot test your submission using the test program, at least check your submission against the YouTube video.
If your submission requires a special command-line option to behave properly, that command-line option counts when calculating your score. However, any interpreter startup time does not count against you, and the test program can be modified to accommodate that if necessary.
Although I doubt one exists, I must say that using a programming language function or library designed specifically for this task is prohibited.

C, 161 154 chars
#define P(d,x)w(d);puts(#x);
w(n){usleep(n<<16);}
y(d){P(d,Y)P(14,M)P(7,C)P(3,A)}
b(){y(664);y(35);y(147);y(35);}
main(){b(b(b(w(34))));y(148);y(33);y(148);}

The tester passes, but only if fflush(stdout); is added after each puts. Since the question clearly states that fflush is not required, I take it as a problem in the tester.
Logic:
w sleeps, the time is given in units of 16.384 65.536 ms. This resolution allows accurate enough timing and small constants (I should perhaps try 100ms).
P waits a while and prints a character.
y prints a YMCA sequence, after an initial delay.
b prints 4 YMCA sequences - this 4*YMCA happens 3 times, with similar enough timing.
main prints the 3*4*YMCA sequences, plus the remaining 3.

"a problem in the tester" - You're right, as apparently pipes are not "interactive" devices :( I will make it use a PTY (which should be more realistic) instead of a pipe as soon as I get the time to.

OK, I changed the tester to use a PTY, and your program passes the test. I also found out about a utility called stdbuf that uses some LD_PRELOAD trick to override the default buffering behavior of the C standard I/O library.

Ruby 180 135 124 118 108 104
[458,k=22,*[97,k,435,k]*2,*[98,k]*2,98].flat_map{|e|[e,9,5,2]}.zip(%w(Y M C A)*15){|a,b|sleep a/1e1;p b}

I just realized there is nothing in the rules prohibiting double quotes around each letter. However, the submission seems to work perfectly :)

The second part of http://codegolf.stackexchange.com/questions/6695/its-fun-to-stay-at-the-y-m-c-a#comment14061_6696 is relevant to you too.

@JPvdMerwe Thanks a lot! You'e right. Dropping two decimals does not have any significant effect. Also, after I did that I noticed that if I tweak the values ±0.1 there are some patterns that allow the array to be constructed in less chars.

Could you do %w(Y M C A)*15 instead of 'Y M C A'.split*15 to generate the letters?  Also that each could probably be a map even though you don't need the output.  Oh, and you can write 10.0 as 1e1!

@chron Thanks! I thought there was nothing much I could do to golf this code even more, but I was obviously wrong. :-)

Instead of using |j|a,b=j, you can use |a,b| directly, and you can save 1 character by assigning 22 to some variable the first time you use it.

Additionally, using [458,k=22,*[97,k,435,k]*2,*[98,k]*2,98] to build the initial array saves another two characters. And flat_map{} is shorter than map{}.flatten.

@Ventero Wow. The k=22 trick is much like GolfScript :.

Thanks everyone for the tips. I guess it's true what they say in the song: "No man does it all by himself". :-)

One last thing: You can pass a block to zip, so no need for the map.

@Ventero edited.

Python2.6 (82)(214)(219)(196)(185)(152)
Fixed. Ran against the video & seems accurate. Saved quiet a few characters by reducing the precision from 3 to 2 in most of the cases(thanks for the tip @JPvdMerwe).
The only problem is that the tester shows a huge discrepancy in the timings. It starts out of sync & tries to come back into sync. In the two test cases it was more than 175 seconds out of sync at the beginning and came back to within 0.342  and 0.451 seconds of being back in sync.
import time;s=time.sleep
for t in[45.8,2.1,9.5,2,43.4,2,9.5,2.1,43.4,2,9.6,2,9.5,2,9.6]*15:
 i=0;s(t)
 while i<4:s([.1,.9,.5,.2][i]);print'YMCA'[i];i+=1

Can you make it run at each of the fifteen times listed above? It also seems that on my machine, you will need to include the -u command line option in the count.

@PleaseStand done, now it runs 15 times. I don't know about adding -u, don't need it on mine. I have Python2.6, if that helps

To clarify, your program should print the first "Y" after approximately 45.766 s, and -u is necessary for the tester program (which uses a pipe), not for output directly to a terminal.

@PleaseStand Yeah, I was wondering about the timing. Was gonna ask you, but you already answered before I had a chance. And about the tester program, is it a requirement that the program runs on your tester as it is, or will you accept submissions that need to be modified to run on the tester, but run fine standalone?

Humm, I can pass my code to the tester without having to use any options

Interesting. I have Python 2.7, and the program (at least when run with -u) loses sync following the first "YMCA". https://gist.github.com/3156422

let us continue this discussion in chat

It's not just you. Mine is losing sync too. I must've fucked something up. Could swear it was working earlier. Back to the drawing board

You can replace 0.930 with 0.93 . Also you can make this quite a bit shorter by only having 2 digits after the decimal point. Doing this will only make a relative change of 0.009 at most which is far less than 0.125 . On this point you can sometimes remove 2 digits say 11.219 to 11.2, because that has a relative difference of 0.019 . The only thing you have to watch for is that you don't compound the differences to too much because of the fact that you have a second delay after the first one.

Thanks @JPvdMerwe. It turns out that with you losing a few miliseconds in some cases and gaining a few in others, it pretty much balances out in the end.

import time followed by s=time.sleep is a bit shorter.

@elssar: I will not count -u against you, as it is only necessary because of a "bug" in the test program.

@uroren didn't know that, thanks!

Mathematica, 157
p=Print[Pause@#;#2]&

(#~p~"Y";.93~p~"M";.465~p~"C";.233~p~"A")&/@{45.766,2.217,9.65,2.144,43.527,2.147,9.591,2.249,43.515,2.162,9.702,2.146,9.661,2.098,9.69}

I watched the entire video to confirm the timing.  Y M C A.... Y M C A...
It could be shorter with less precision, but then I'd have to watch the video again to confirm that it was not off by more than .125 at the end. lol

JavaScript (Node.js), 206 bytes
s=async t=>await new Promise(r=>setTimeout(r,t*1e3));(async _=>{for(t of[45.8,2.1,9.5,2,43.4,2,9.5,2.1,43.4,2,9.6,2,9.5,2,9.6])for(i=0,await s(t);i<4;)await s([.1,.9,.5,.2][i])||console.log('YMCA'[i++])})()

Try it online!
i tried out the tester program and it was within about half a second for each cue but not 0.125. i think the startup time just needs to be factored in and some of the deltas may need to be adjusted to account for accumulated rounding errors.
i'm curious if there may be a shorter solution without using >ES5 await, and a shorter way to print to STDOUT.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/