if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)

However, you can implement an interface with a function like so :

Comparator<String> c = new Comparator<String>() {
    int compare(String s, String s2) { ... }
};

and you can use this with inner classes to get an almost-anonymous function :)

Answer from chris on Stack Overflow
Top answer
1 of 6
86

if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)

However, you can implement an interface with a function like so :

Comparator<String> c = new Comparator<String>() {
    int compare(String s, String s2) { ... }
};

and you can use this with inner classes to get an almost-anonymous function :)

2 of 6
48

Here's an example of an anonymous inner class.

System.out.println(new Object() {
    @Override public String toString() {
        return "Hello world!";
    }
}); // prints "Hello world!"

This is not very useful as it is, but it shows how to create an instance of an anonymous inner class that extends Object and @Override its toString() method.

See also

  • JLS 15.9.5 Anonymous Class Declarations

Anonymous inner classes are very handy when you need to implement an interface which may not be highly reusable (and therefore not worth refactoring to its own named class). An instructive example is using a custom java.util.Comparator<T> for sorting.

Here's an example of how you can sort a String[] based on String.length().

import java.util.*;
//...

String[] arr = { "xxx", "cd", "ab", "z" };
Arrays.sort(arr, new Comparator<String>() {
    @Override public int compare(String s1, String s2) {
        return s1.length() - s2.length();
    }           
});
System.out.println(Arrays.toString(arr));
// prints "[z, cd, ab, xxx]"

Note the comparison-by-subtraction trick used here. It should be said that this technique is broken in general: it's only applicable when you can guarantee that it will not overflow (such is the case with String lengths).

See also

  • Java Integer: what is faster comparison or subtraction?
    • Comparison-by-subtraction is broken in general
  • Create a Sorted Hash in Java with a Custom Comparator
  • How are Anonymous (inner) classes used in Java?
🌐
W3Schools
w3schools.com › java › java_anonymous.asp
Java Anonymous Class
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A ... An anonymous class is a class without a name.
Discussions

What makes an anonymous function different from an anonymous class?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
3
1
October 23, 2023
Java 8 lambda performance is not great

My assumption is, that Lambdas are a new feature, and JVM optimization are not at the level of native loops yet.

Also you use different method calls in comparison. If you use Double::compare you can not compare it with d < min in performance.

More on reddit.com
🌐 r/java
26
11
January 18, 2015
Carry Local Vars Into Anonymous Function?
you'd expect it to work like any other functional language but... nope, gml gonna gml More on reddit.com
🌐 r/gamemaker
21
17
December 13, 2020
[Java] ELI5 Lambda expressions
Lambda expressions are, for the most part, a more concise way of writing something that previously would have required a class instance (usually an anonymous class) to implement. So if you understand how and why anonymous classes are used, you can figure out lambda expressions. If you don't, then your first step should be to understand those. Java does not have function pointers. Function pointers are used in C and C++ extensively. They are a way of passing functions to other functions. In Lisp you can do that directly, because functions are so-called "first class objects", but in C you have to pass a pointer to some function X and then the function you are calling can call X via the pointer. But, Java doesn't have these. What you do for Java is pass in an object with an implemented method and whatever you are calling will call the method in that class. This is done something like: someObject.foo(new Bonk() { void bonk(String who) { System.out.println("I'm bonking you, " + who); }); This looks a little confusing, but what we are doing is defining a new class (and not giving it a name) and creating an instance of that class at the same time, and then passing that instance to foo. You could do this as something like: class MyBonk implements Bonk { void bonk(String who) { System.out.println("I'm bonking you, " + who); } } MyBonk bonker = new MyBonk(); someObject.foo(bonker); But the first way is much, much terser, right? I love anonymous classes, but I'm a closet LISP programmer, so that would figure. Anyway, lambda functions are a mostly syntactic shortcut for anonymous classes (although there are JVM changes as well, for reasons that I have not investigated). If you have an anonymous class with just one method then it's pretty obvious that the purpose of that class is to call that method. Anonymous functions remove even more of the cruft and you say: someObject.foo(who -> System.out.println("I'm bonking you, " + who); And every LISP programmer in the world says "Wow, we figured this out over half a century ago". More on reddit.com
🌐 r/learnprogramming
12
37
July 14, 2016
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › lambdaexpressions.html
Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
Lambda expressions enable you to do this, to treat functionality as method argument, or code as data. The previous section, Anonymous Classes, shows you how to implement a base class without giving it a name. Although this is often more concise than a named class, for classes with only one method, even an anonymous class seems a bit excessive and cumbersome.
🌐
Medium
medium.com › @nagarjun_nagesh › lambda-functions-vs-anonymous-inner-classes-in-java-80893c2214d5
Lambda Functions vs. Anonymous Inner Classes in Java | by Nagarjun (Arjun) Nagesh | Medium
February 23, 2024 - Java 8 introduced the `java.util.function` package, which includes several built-in functional interfaces, such as `Function`, `Consumer`, `Predicate`, and `Supplier`, to name a few. These functional interfaces make it easier to work with lambda expressions and enhance the readability of code when dealing with functions. Lambda functions, also known as lambda expressions, are a concise way to represent anonymous functions in Java.
🌐
Reddit
reddit.com › r/javahelp › what makes an anonymous function different from an anonymous class?
r/javahelp on Reddit: What makes an anonymous function different from an anonymous class?
October 23, 2023 -

To me, an anonymous function sounds like it is an anonymous class but with a single method to implement. So why give it a fancy name such as an anonymous function when we could have called it an anonymous class with a single function?

Top answer
1 of 3
3
Java doesn't have "anonymous functions" and I don't see that term being used except by perhaps people used to languages where they do exist or trying to draw parallels with them. In the Java world, they are typically called lambda's. A lambda is an instance of a class which has a single function (method). Often these classes have a functional interface. Also see: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
NashTech Blog
blog.nashtechglobal.com › home › anonymous functions in java : begineers
Anonymous Functions in JAVA : Begineers - NashTech Blog
November 2, 2021 - Because,These are a form of nested function in allowing access to variables in the scope of the containing function (non-local functions).So,This means anonymous functions need to be implemented using closures.Simply, lambda is an anonymous function which can be passed around in a concise way.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › lambda-expressions-java-8
Java Lambda Expressions - GeeksforGeeks
lambda expressions, introduced in Java 8, allow developers to write concise, functional-style code by representing anonymous functions.
Published: August 29, 2026
🌐
Wikipedia
en.wikipedia.org › wiki › Anonymous_function
Anonymous function - Wikipedia
1 month ago - For example, the ML languages are ... Pascal, has been extended to support anonymous functions, as has C++ (by the C++11 standard). Second, the languages that treat functions as first-class functions (Dylan, Haskell, JavaScript, Lisp, ML, Perl, Python, Ruby, Scheme) generally ...
🌐
Quora
quora.com › Can-we-call-the-Lambda-expressions-in-Java-anonymous-functions
Can we call the Lambda expressions in Java, anonymous functions? - Quora
Answer (1 of 3): Oooofff…lots of misinformation here so I’m afraid I’m going to have to step in. Let’s fix with the question itself, which messes up concepts and punctuation. Q: Can we call lambdas in Java “anonymous functions”? A: Think of lambdas in Java as being inline functions ...
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › anonymousclasses.html
Anonymous Classes (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
Anonymous classes are ideal for implementing an interface that contains two or more methods. The following JavaFX example is from the section Customization of UI Controls. The highlighted code creates a text field that only accepts numeric values.
🌐
DZone
dzone.com › coding › java › java lambda expressions basics
Java Lambda Expressions Basics
April 13, 2013 - A lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (->) and a function body. The following are examples of Java lambda expressions:
🌐
Quora
quora.com › Is-Java-Lambda-function-syntactic-sugar-for-using-an-anonymous-inner-class-implementing-a-functional-interface-in-Java
Is Java Lambda function syntactic sugar for using an anonymous inner class implementing a functional interface in Java? - Quora
Answer (1 of 2): In terms of the language syntax, yes. However, the implementation is very different, and can be optimised more. Where there really is a difference from anonymous inner classes is that lambdas can be replaced with method references where the method signature looks like an impleme...
🌐
Medium
medium.com › @himaja.gudluri1997 › java-script-anonymous-function-examples-and-detailed-explanation-ba9faa4bb484
java script: anonymous function examples and detailed explanation | by Himaja gudluri | Medium
January 16, 2025 - java script: anonymous function examples and detailed explanation What is an Anonymous Function in JavaScript? An anonymous function is a function that is defined without a name. It is typically used …
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Classes
Classes - JavaScript | MDN
May 22, 2026 - Classes are in fact "special functions", and just as you can define function expressions and function declarations, a class can be defined in two ways: a class expression or a class declaration. ... // Declaration class Rectangle { constructor(height, width) { this.height = height; this.width = width; } } // Expression; the class is anonymous but assigned to a variable const Rectangle = class { constructor(height, width) { this.height = height; this.width = width; } }; // Expression; the class has its own name const Rectangle = class Rectangle2 { constructor(height, width) { this.height = height; this.width = width; } };
🌐
Refactoring.Guru
refactoring.guru › home › design patterns › behavioral patterns
Strategy
January 1, 2026 - A lot of modern programming languages have functional type support that lets you implement different versions of an algorithm inside a set of anonymous functions.
🌐
Programiz
programiz.com › java-programming › lambda-expression
Java Lambda Expressions (With Examples)
Since we know that a functional interface has just one method, there should be no need to define the name of that method when passing it as an argument. Lambda expression allows us to do exactly that. Lambda expression is, essentially, an anonymous or unnamed method.
🌐
Big-O Cheat Sheet
bigocheatsheet.com
Big-O Algorithm Complexity Cheat Sheet (Know Thy Complexities!) @ericdrowell
Hi there! This webpage covers the space and time Big-O complexities of common algorithms used in Computer Science. When preparing for technical interviews in the past, I found myself spending hours crawling the internet putting together the best, average, and worst case complexities for search ...
🌐
Medium
medium.com › @gulhanemadhuri1 › java-8-lambda-function-2854a5a382be
Java 8 Lambda Function. Lambda Expression: An anonymous… | by Madhu | Medium
October 19, 2024 - Java 8 Lambda Function Lambda Expression: An anonymous function; a method without a name. Has method parameters, method body, and return type. Not tied to any class. Can be assigned to a variable and …
🌐
Medium
bankymono.medium.com › how-to-define-anonymous-classes-in-java-58cadb0d1dd1
How to define anonymous classes in Java | by bankymono | Medium
April 11, 2024 - An anonymous class is a class that is defined without a name. It implements an interface or extends a class while also instantiating an…