Sign in to follow this  
5MinuteGaming

[java] Shortest Hello World! in Java

Recommended Posts

5MinuteGaming    274
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);
	}
	
}

Share this post


Link to post
Share on other sites
shmoove    821
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

Share this post


Link to post
Share on other sites
Addictman    218
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).

Share this post


Link to post
Share on other sites
Alrecenk    400
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!") ;}}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this