JavaCodingNerd

Java Coding Nerd. This Blog will feature content-rich articles, tutorials and own opinions on variuos programming related topcis.

Java Riddles

Java Riddle: A different kind of “Hello World”

Java Riddle Hello World

Java Riddle

Propably 99,99% of all developers started their career/hobby with a Hello World example. In this Riddle we will come back to this but in a subtle diffirent way.

So first of all the contraints and in fact there is only one!

DO NOT WRITE ANY CODE IN THE MAIN METHOD!
Other than that feel free to do whatever you want.

Print Hello World without any line of Code in the main method

So here is the class you can work with. Just copy paste it into your IDE or write your own.


public class HelloWorld_Riddle {

//Write code here

public static void main(String[] args) {

//Do not write any code here
}

//Write code here

}

As you can see, you can see nothing. Now try to make the programm print “Hi World” “Hello Planet” or whatever you want to the console considering the given constraint.

You need some hints?

If you want some hints make sure that you mark the lines below.

  • static
  • initialization
  • static initialization

If you still cannot find a solution check out this link

https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

The solution

In Java there is a concept named static initalization blocks. Those blocks will always initialized when the class is loaded. They are executed in the order they are declared. An these will always be the first thing a class will load when it is used. Since the main method is part of our class the static initialization block will be executed eventhough the method itself is empty. Therefore we have a solution that can look like this.


public class HelloWorld_Riddle {

//Write code here
static
{
System.out.print("Hello ");
}

public static void main(String[] args) {

//Do not write any code here
}

static
{
System.out.println("World");
}
//Write code here

}

If you have any other solution or question feel free to comment

 

Spread the love

Leave a Reply

Theme by Anders Norén