Jump to content
  • Advertisement
Sign in to follow this  
5MinuteGaming

[java] Shortest Hello World! in Java

This topic is 4059 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!