[java] Shortest Hello World! in Java

Started by
6 comments, last by Lucidquiet 16 years, 11 months ago
I just found this out from a friend of mine and thought that it was an interesting hack. He originally used a static member variable with a constructor and then I used my knowledge of static blocks to simplify it even more.

public class Test {

	static {
		System.out.println("Hello World!");
		System.exit(0);
	}
	
}

Advertisement
static blocks I understand.

But how does a variable have its own constructor? Please explain.
Quote:Original post by Kevinator
static blocks I understand.

But how does a variable have its own constructor? Please explain.


Methinks he means something like this:
public class Test{  static Test x;  public Test()  {    System.out.println("Hello World!");    System.exit(0);  }}

When the class is loaded the Test constructor is called for "x".

shmoove
Static initialization blocks are what the name indicates, initialization blocks that are static.

They are similar to methods with no name, arguments, or return types. You can include any number of static initializer blocks within the class definition, and seperate them by other code such as method definitions and constructors as you please. The static blocks will be executed in the order which they appear in the code, regardless of other code.

Since they are static, they are executed when the CLASS is loaded, - not when an instance is loaded. So they will be executed even if you do not plan to instanciate the class at all.

As an example:

public class StaticBlockTest{	private static int foo;	private static int bar;		static	{		foo=3;		bar=4;		System.out.println("Foo: "+foo+"\tBar: "+bar);		System.out.println( System.nanoTime() );	}		public StaticBlockTest()	{		foo=5;		bar=6;		System.out.println("Foo: "+foo+"\tBar: "+bar);		System.out.println( System.nanoTime() );	}		static	{		foo=7;		bar=8;		System.out.println("Foo: "+foo+"\tBar: "+bar);		System.out.println( System.nanoTime() );	}		public static void main(String[] args)	{			}}


The previous code will output the foo=3/bar=4, and foo=7/bar=8 lines, but not the line within the constructor (we never create an instance).
Development blog, The Omega Sector -- http://www.omegasector.org
Note: The hack will not work in Eclipse.

- Rob
If you're really going for the shortest hello world you don't need to make your class public and I'd just let it throw the main not found error.

class h{static{System.out.println("Hello world!") ;}}
You could always go with the shorter print method over println. ;)
Oh the things we do to amuse ourselves.

L-
"Education is when you read the fine print; experience is what you get when you don't." -Pete Seegerwww.lucid-edge.net

This topic is closed to new replies.

Advertisement