Wastefully creative "Hello World" output method list (Java)

Overview

When you start learning a language, the first program you write will usually output "Hello World". In the case of Java, the output is as follows.

HelloWorld.java


public class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

However, there may be a better output method. I would like to try various things this time.

Program example

Specified in hexadecimal

Specify one character at a time in Unicode.

HelloWorld.java


public class HelloWorld {
	public static void main(String[] args) {
		String helloWorld = new String("\u0048" + 
				"\u0065" + 
				"\u006c" + 
				"\u006c" + 
				"\u006f" + 
				"\u0020" + 
				"\u0057" + 
				"\u006f" + 
				"\u0072" + 
				"\u006c" + 
				"\u0064");
		System.out.println(helloWorld);
	}
}

Execution result: Hello World

Specified in binary

First, specify the characters in binary, convert them to hexadecimal, then convert them to characters and output.

HelloWorld.java


public class HelloWorld {
	public static void main(String[] args) {
		//Hold binary number
		String[] helloWorldLetters = {"1001000",
				"1100101",
				"1101100",
				"1101100",
				"1101111",
				"100000",
				"1010111",
				"1101111",
				"1110010",
				"1101100",
				"1100100"};
		
		//Convert the above array to hexadecimal. Put the conversion result in the variable "line"
		String line = "";
		for (String helloWorldLetter:helloWorldLetters) {
			int decimal = Integer.parseInt(helloWorldLetter, 2);
			//Convert binary to hexadecimal
			String hex = Integer.toHexString(decimal);
			//Convert hexadecimal to Unicode
			char letter = (char)Integer.parseInt(hex,16);
			line += letter;
		}
			
		String helloWorld = new String(line);
		System.out.println(helloWorld);
	}
}

Execution result: Hello World

"Hello" and "World" creation processes are threaded and executed in parallel

Hello and World are created at the same time using thread processing, and output after waiting for both processing to be completed. If it is Runnable, it cannot have a return value, so implement it using Callable. First, here is the code that calls the thread.

HelloWorld.java


package HelloWorld;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class HelloWorld {

	public static void main(String[] args) {
		//Variable to store the result
		String helloWorld;
		
		//Creating a thread
		ExecutorService service = Executors.newFixedThreadPool(2);
		Future<String> future1 = service.submit(new HelloWorldCallable(0));
		Future<String> future2 = service.submit(new HelloWorldCallable(1));
		try {
			//Combine the returned values into one
			helloWorld = future1.get() + future2.get();
			System.out.println(helloWorld);
		}catch(Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

Here is the code on the called side.

HelloWorldCallable.java


package HelloWorld;

import java.util.concurrent.Callable;

public class HelloWorldCallable implements Callable<String>{
	//Keep what number was called
	private int num;
	
	public HelloWorldCallable(int num) {
		this.num = num;
	}
	
	public String call() {
		if(this.num == 0) {
			return "Hello ";
		}else {
			return "World";
		}
	}
}

Execution result Hello World

Created character by thread by thread processing

In the above example, it is divided into only "Hello" and "World", but in any case, I will try to separate each character.

HelloWorld.java


package HelloWorld;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class HelloWorld {

	public static void main(String[] args) {
		//Variable to store the result
		String helloWorld = "";
		//Store results from threads
		List<Future<String>> futures = new ArrayList<Future<String>>();
		
		//Creating a thread
		ExecutorService service = Executors.newFixedThreadPool(10);
		for(int i = 0; i < 11; i++) {
			futures.add(service.submit(new HelloWorldCallable(i)));
		}
		try {
			for (Future<String> future:futures) {
				if(future.isDone()) {
					helloWorld += future.get();
				}
			}
			System.out.println(helloWorld);
		}catch(Exception e) {
			System.out.println(e.getMessage());
		}
	}
}

HelloWorldCallable.java


package HelloWorld;

import java.util.concurrent.Callable;

public class HelloWorldCallable implements Callable<String>{
	private static String[] message = {"H","e","l","l","o"," ","W","o","r","l","d"};
	//Keep what number was called
	private int num;
	
	public HelloWorldCallable(int num) {
		this.num = num;
	}
	
	public String call() {
		return message[num];
	}

}

Execution result: Hello World The Static variable of the HelloWorldCallable class has something similar to "Hello World" written in it, but don't worry.

Scraping and outputting "Hello World" from the web

The characters are taken from the title of this page of the Japanese version of Wikipedia. Screen Shot 2018-09-08 at 11.24.43.png

HelloWorld.java


import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class HelloWorld {
	public static void main(String[] args) {
    	System.setProperty("webdriver.chrome.driver", "Where the chrome driver is located");
    	WebDriver driver = new ChromeDriver();

    	//Website to get information
    	String url = "https://ja.wikipedia.org/wiki/Hello_world";
    	//HTML element that describes the information you want to get (this time the class name of the title of Wikipedia)
    	String target = "firstHeading";
    	
    	driver.get(url);
    	//Multiple results may be obtained because it is specified by the class name.
    	List<WebElement> values = driver.findElements(By.className(target)); 
    	for (WebElement t : values){
    	    String value = t.getText();
    	    //If it is left as it is, "Hello world" will be output, so convert "w" to uppercase.
    	    String str = value.substring(0, 6)
    	    		+ value.substring(6, 7).toUpperCase()
    	    		+ value.substring(7);
    	    System.out.println(str);
    	}
	}
}

Execution result: Hello World

Scraping and outputting character by character from the web

In the above example, all the character strings are taken from one site, but here is a method to take each character from a different place without such ease. The source of each character is the title part of the following page of English Wikipedia.

letter Wiki title Japanese translation(Category)
H Harry Potter Harrypotter(movies)
e The Human Centipede Humancentipede(Legendarymovie)
l Flying Spaghetti Monster FlyingSpaghettiMonster(Religion)
l Lil Wayne LilWayne(Wrapper)
o Konjac Konjac(food)
- Null Pointer Nullpointerexception(exception)
W Wikipedia Wikipedia(Wikipedia)
o Morgan Freeman MorganFreeman(Actor)
r Starbucks Starbucks(Company)
l Family guy FamilyGuy(Anime)
d Angry Birds AngryBirds(game)

HelloWorld.java


import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class HelloWorld {
	public static void main(String[] args) {
		//Keep Wiki page
		String[] url = {"Harry_Potter",
				"The_Human_Centipede_(First_Sequence)",
				"Flying_Spaghetti_Monster",
				"Lil_Wayne",
				"Konjac",
				"Null_pointer",
				"Wikipedia",
				"Morgan_Freeman",
				"Starbucks",
				"Family_Guy",
				"Angry_Birds"};
		//Holds the number of the target character in the title
		int[] location = {0,2,1,2,1,4,0,1,3,4,9};
		
		String helloWorld = makeHelloWorld(url,location);
		System.out.println(helloWorld);
	}
	
	private static String makeHelloWorld(String[] url, int[] location) {
    	System.setProperty("webdriver.chrome.driver", "Where the chrome driver is located");
    	WebDriver driver = new ChromeDriver();
    	
    	//Variable that holds the result
    	String result = "";
    	//HTML element with the string to retrieve(This time the class name of the title part)
    	String target = "firstHeading";
    	
    	for (int i = 0; i < url.length; i++) {
    		driver.get("https://en.wikipedia.org/wiki/" + url[i]);
    		//Get characters from HTML elements
        	List<WebElement> values = driver.findElements(By.className(target)); 
        	for (WebElement t : values){
        	    String value = t.getText();
        	    //Cut out one character from the acquired character string
        	    char letter = value.charAt(location[i]);
        	    result += letter;
        	}
    	}
    	return result;
	}
}

Execution result: Hello World It took a lot longer than before.

The "Hello World" and translated by Google API output

People who do not want that type in Nante's "Hello World" in English in the first place, let it write "Hello World" is translated using Google's API in Japanese. Google's Cloud Translation API used here, but if you make a request like https://www.googleapis.com/language/translate/v2?key=your key & q = Hello & source = en & target = ja, Screen Shot 2018-09-08 at 16.02.22.png You will get a response like this. Let's use it immediately

HelloWorld.java


package HelloWorld;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

public class HelloWorld {

	public static void main(String[] args) {
		//Japanese before translation
		String ja = "Hello World";
		
		//Key to using Google API
		String key = "Your key";
		String baseUrl = "https://www.googleapis.com/language/translate/v2?key=";
		//Create a url to send the request to
		String urlText = baseUrl + key + "&q=" + ja + "&source=ja&target=en";
		
		try {
			//Communicate
			URL url = new URL(urlText);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//Specify GET method
			conn.setRequestMethod("GET");
			InputStream in = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder output = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				output.append(line);
			}
			//Convert response content to JSONObject type
			JSONObject json = new JSONObject(output.toString());
			//Dig into the part where the result is stored
			JSONObject data = json.getJSONObject("data");
			JSONArray translations = data.getJSONArray("translations");
			JSONObject firstItem = (JSONObject)translations.get(0);
			String result = firstItem.getString("translatedText");
			System.out.println(result);
		}catch(IOException e) {
			System.out.println(e.getMessage());
		}
	}

}

Execution result: Hello World You could output Hello World without using English.

Create a Servlet on the virtual server that just returns "Hello World"

This time, create a Servlet that just returns the response "Hello World", upload it to the virtual server, and create a program that gets the character string of "Hello World" by accessing it. First of all, the Servlet part.

HelloWorld.java


package HelloWorld;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet{

//When called by the GET method
public void doGet(HttpServletRequest request, HttpServletResponse response)
		      throws ServletException, IOException {
	   
      response.setContentType("text/plain");

      PrintWriter out = response.getWriter();
      out.println("Hello World");
   }
}

I will upload this to the virtual server created using Virtual Box. I will explain briefly assuming that Apache and Tomcat are installed. First, create the following directories.

tomcat
   ┣ webapps
     ┣ HelloWorld (Newly added below)
        ┗ WEB-INF
           ┣ web.xml(I will explain later)
           ┗ classes
              ┗ HelloWorld
                            ┗ HelloWorld.java (The one with the source code on top)
     ┣ docs
     ┣ examples
     ┣ host-manager
     ┗ manager
  ┗ work

By playing with web.xml, you can link the request url and the Servlet file. The description of web.xml is as follows.

web.xml


<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
  version="2.4">

  <servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>HelloWorld.HelloWorld</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>HelloWorld</servlet-name>
    <url-pattern>/HelloWorldApi</url-pattern>
  </servlet-mapping>

</web-app>

In addition, we will play with the Apache settings. Add the following description at the bottom of httpd.conf (I think it is in / etc / httpd / conf / for CentOS). ProxyPass /HelloWorld/ ajp://localhost:8009/HelloWorld/ Now the request under / HelloWorld will be passed from Apache to Tomcat.

Compile with the javac command and the Servlet part is complete. If you try hitting the url from the browser, you can see that the information is properly obtained as shown below. Screen Shot 2018-09-08 at 19.43.20.png

Finally, create a class that uses this Servlet.

HelloWorld.java


package HelloWorld;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HelloWorld{
	public static void main(String[] args) {
		try {
			//Url to make a request to Servlet
			URL url = new URL("http://192.168.33.10/HelloWorld/HelloWorldApi");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			InputStream in = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder output = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null) {
				output.append(line);
			}
			System.out.println(output.toString());
		}catch(IOException e) {
			System.out.println(e.getMessage());
		}
	}
}

Execution result: Hello World I can get the information properly.

Place the Servlet in docker instead of virtual server

In the above example, the Servlet was placed on the virtual server, but we will create an Apache and Tomcat environment with docker and place the Servlet there. I referred to @ shintaro123's article. First, create the following directory.

docker
┣ httpd
  ┣ Dockerfile (※1)
  ┣ httpd-proxy.conf
  ┗ run-httpd.sh
┗ tomcat
  ┣ Dockerfile (※2)
┣ Hello World (Hereafter is the same as above)
    ┗ WEB-INF
      ┗ web.xml
        ┗ classes
          ┗ HelloWorld
                     ┗ HelloWorld.java 
   ┗ docker-compose.yml (※3)

/docker/httpd/Dockerfile


FROM centos:7
  
RUN yum -y update && yum clean all
RUN yum -y install httpd httpd-devel gcc* make && yum clean all

ADD httpd-proxy.conf /etc/httpd/conf.d/
ADD run-httpd.sh /run-httpd.sh
RUN chmod -v +x /run-httpd.sh

CMD ["/run-httpd.sh"]

/docker/tomcat/Dockerfile


FROM tomcat:9.0.1-alpine

COPY HelloWorld /usr/local/tomcat/webapps/HelloWorld/

RUN rm -rf /usr/local/tomcat/webapps/ROOT

CMD ["catalina.sh","run"]

/docker/docker-compose.yml


version: '3'
services:
  httpd:
    container_name: httpd-container
    build: ./httpd
    ports:
      - "80:80"
  tomcat:
    container_name: tomcat-container
    build: ./tomcat
    expose:
      - "8009"
volumes:
  data: {}

cd to / docker /

docker-compose build --no-cache
docker-compose up -d

You can get information from the Servlet by typing the command. The file that outputs Hello World is the same as when the Servlet is placed on the virtual server.

Generate a random character string, wait for "Hello World" and output

This is the idea of Kilisame. It creates a character string at random and outputs it when it becomes "Hello World". If the character string is generated completely randomly, it will not end forever, so it will be randomly selected from eight types of characters, "H", "e", "l", "o", "", "W", "r", and "d". Make a line.

HelloWorld.java


package HelloWorld;

import java.util.Random;

public class HelloWorld{
	public static void main(String[] args) {
		final String[] letters = {"H","e","l","o"," ","W","r","d"};
		
		Random random = new Random();
		//Holds a randomly generated string
		String helloWorld = "";
		//If true, exit the while statement below
		boolean done = false;
		//Since it's a big deal, keep track of how many loops you succeeded in
		double count = 0;
		while (done == false) {
			count += 1;
			helloWorld = "";
			for (int i = 0; i < 11; i++) {
				int randomNum = random.nextInt(8);
				String helloChar = letters[randomNum];
				helloWorld += helloChar;
			}
			if(helloWorld.equals("Hello World")) {
				done = true;
			}
			System.out.println(helloWorld);
		}
		System.out.println(helloWorld);
		System.out.println("At " + count + "th Time");
		
	}

}

Execution result: Hello World At 7.98865771E8th Time 798,685,771st success

Summary

Hello World seems to be good to output normally. If you come up with a more complex Hello World output method, write it in the comments.

Recommended Posts

Wastefully creative "Hello World" output method list (Java)
Java, Hello, world!
Java Hello World
"Hello World" in Java
Java Learning (1)-Hello World
Build Java environment and output hello world [Beginner]
Hello World in Java
java hello world, compile, run
Java beginners read Hello World
Java method list (memorial) (under construction)
Hello World for ImageJ Java Plugin
Hello World on AWS Lambda + Java
Hello World in java in eclipse now
Hello world in Java and Gradle
Java method
java (method)
Hello world with Java template engine Thymeleaf
List method
Java development with Codenvy: Hello World! Run
Java method
Hello World on Mac VS Code Java
[Java] method
Minimal Java environment construction and Hello World
[Java] method
Output Hello World in kotlin's simple main function
Until you install Gradle and output "Hello World"
[Java] Hello World with Java 14 x Spring Boot 2.3 x JUnit 5 ~
Display "Hello World" in the browser using Java
Display "Hello World" in the browser using Java
[Java] output, variables
Java memorandum (list)
Clone Java List.
Java8 method reference
Read "Hello world"
[Java] forEach method
Hello Java Lambda
java8 method reference
[Java] Random method
[Java] split method
About List [Java]