3

I know that there is a way to have a method to run automatically in java?. This is known as an IIFE in javascript, but is this possible in java?

Javascript IIFE:

(function() {
    console.log('Hello!');    
})();

Thank You! (I'm also just curious)

jfriend00
  • 683,504
  • 96
  • 985
  • 979
mashedpotats
  • 324
  • 2
  • 16

7 Answers7

5

Here's an IIFE in Java:

((Function<String, String>) s -> {
    String z = "'" + s + "'";
    return z;
}).apply("aaa");
akim
  • 8,255
  • 3
  • 44
  • 60
Moika Turns
  • 677
  • 11
  • 17
  • 1
    It does work. The key ingredient here is the cast that defines the interface of the lambda, without which one would not know how to invoke the lambda ([`apply`, or `get`, or...](https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html)). – akim Jul 13 '21 at 14:29
1

All of the following print "Hello world!"

JavaScript:

console.log((function() {
  const x = "Hello world!";
  return x;
})());

Java:

System.out.println(((Supplier<String>) () -> {
  String x = "Hello world!";
  return x;
}).get());

In Java it may feel more ergonomic to create a helper function to infer the type and execute the function for you:

public static <T> T iife(Supplier<? extends T> supplier) {
  return supplier.get();
}
...
System.out.println(iife(() -> {
  String x = "Hello world!";
  return x;
}));

In general you might want to consider factoring out the function. But if the function is relatively small, and especially if it captures several variables, an IIFE may be more readable. I liken an IIFE to a block expression (which Java does not have).

Daniel Avery
  • 159
  • 1
  • 4
0

Stumbled upon this question when looking for this idea myself. I think the closest thing Java has to JavaScript IIFEs would be an instance of an abstract class, whose only method, an execute method, is overriden during the instance creation and then executed immediately after the object's instantiation. You can even get the closure aspect of it too. However, you won't be able to change what the variable refers to inside the overriden method.

JavaScript:

let subject = 'World';

(() => {
    console.log(`Hello, ${subject}!`);
})();

Java:

public abstract class Iife {
    public abstract void execute();
}

public class Main {

    public static void main(String[] args) {
        String subject = "World";

        new Iife() {
            @Override
            public void execute() {
                System.out.println("Hello, " + subject + "!");
            }
        }.execute();
    }
}
Matt Welke
  • 1,441
  • 1
  • 15
  • 40
  • How do I make one that returns a variable like a String, int, boolean, etc.? – Diriector_Doc Nov 06 '18 at 02:19
  • To make a "Java IIFE" that returns a String, int, boolean, etc, you would change the return type of the `execute` method to match. In my example above, I return `void` because the IIFE was just supposed to run and not return anything. I could have just as easily made the `execute` signature `public abstract int execute();`. However, usually IIFE's are only meant to be executed for their side effects (like starting a program with its own scope) instead of for their return type. It sounds like this may not be what you're looking for. – Matt Welke Nov 09 '18 at 04:28
0

There is no direct way as mentioned by other people above.

Anonymous Inner Class with init() Initializer

I feel that this could be used like IIFEs but the problem is that it needs to be inside another class

Thread T  = new Thread() {
    private int num;
    Thread init(int num){
        this.num = num;
        return this;
    }
    @Override
    public void run() {
        // computes and outputs the factorial of num
        int res = 1;
        for (int i = 1; i <= num; i++) {
            res *= i;
        }
        System.out.println(res);
    }
}.init(3);

The init() can be used to pass parameters to be used for working

Alan Sereb
  • 2,358
  • 2
  • 17
  • 31
-1

Java will automatically run the "public static void main(String[] args)" method in the class specified.

-1

In a static context, you can define code wrapped within brackets using the static modifier:

public class MyClass{
    static{
        System.out.println("Running static");
    }
}

In the context of Objects, you can wrap the code in the same manner without the static modifier:

public class MyClass{

    {
        System.out.println("Initializing");
    }

}
copeg
  • 8,290
  • 19
  • 28
  • Thank you for this. I'm also presuming you can run almost any code in these "methods" right? – mashedpotats May 21 '15 at 00:13
  • 1
    It is context dependent, but code that is accessible can be placed in these blocks Note this is not equivalent to an IIFE, `static` block is loaded at class loading (see http://stackoverflow.com/questions/3499214/java-static-class-initialization), and the other non-static block on instance construction. – copeg May 21 '15 at 13:22
-1

There is no IIFE in java.

Java is statically typed & compiled as opposed to javascript which is dynamically typed and interpreted.

In java there is only one entry point to a program which is the method main which is static and public.

In Groovy (JVM base language) you can use repl where defined method (functions are method in java terminology) can be invoked later which may be the nearest thing to IIFE.

Master Mind
  • 3,014
  • 4
  • 32
  • 63
  • 1
    Might want to reconsider whether 'There is no IIFE in java' is the case. The example I provided above seems to satisfy the definition of an IIFE: https://developer.mozilla.org/en-US/docs/Glossary/IIFE – Moika Turns Dec 14 '18 at 09:18