Return to site

JBang: Run java as scripts anywhere.

· java

1) Given this class:

import com.github.lalyos.jfiglet.FigletFont;
import java.util.Scanner;
class hello {

    public static void main(String... args) throws Exception {
    Scanner scanner = new Scanner(System.in);

    //  prompt for the user's name
    System.out.print("Enter your name: ");

    // get their input as a String
    String username = scanner.next();

    // prompt for their age
    System.out.print("Enter your age: ");

    // get the age as an int
    int age = scanner.nextInt();
	
    System.out.println(FigletFont.convertOneLine(String.format("%s, your age is %d", username, age)));
    }
}

2) Open Powershell in Windows, typing "PowerShell" in Cortana search box.

3) Change of directory in PowerShell to the directory containing the "hello.java" file:

cd my_directory

4) Execute this command line in PowerShell:

iex "& { $(iwr https://ps.jbang.dev) } ./hello.java"

BANG!!!

Here you go, you are executing Java code in a very trivial way!

Section image