Why it is not allowing AppTest::makeUppercase?

The short answer is that AppTest::makeUppercase isn't valid "reference to an instance method of an arbitrary object of a particular type". AppTest::makeUppercase must implement interface Function<AppTest, String> to be valid reference.

Details:

There are 4 kinds of method references in Java:

  1. ContainingClass::staticMethodName - reference to a static method
  2. containingObject::instanceMethodName - reference to an instance method of a particular object
  3. ContainingType::methodName - reference to an instance method of an arbitrary object of a particular type
  4. ClassName::new - reference to a constructor

Every single kind of method reference requires corresponding Function interface implementation. You use as a parameter the reference to an instance method of an arbitrary object of a particular type. This kind of method reference has no explicit parameter variable in a method reference and requires implementation of the interface Function<ContainingType, String>. In other words, the type of the left operand has to be AppTest to make AppTest::makeUppercase compilable. String::toUpperCase works properly because the type of parameter and type of the instance are the same - String.

import static java.lang.System.out;

import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;

class ReferenceSource {

    private String value;

    public ReferenceSource() {
    }

    public ReferenceSource(String value) {
        this.value = value;
    }

    public String doInstanceMethodOfParticularObject(final String value) {
        return ReferenceSource.toUpperCase(value);
    }

    public static String doStaticMethod(final String value) {
        return ReferenceSource.toUpperCase(value);
    }

    public String doInstanceMethodOfArbitraryObjectOfParticularType() {
        return ReferenceSource.toUpperCase(this.value);
    }

    private static String toUpperCase(final String value) {
        return Optional.ofNullable(value).map(String::toUpperCase).orElse("");
    }
}

public class Main {
    public static void main(String... args) {
        // #1 Ref. to a constructor
        final Supplier<ReferenceSource> refConstructor = ReferenceSource::new;
        final Function<String, ReferenceSource> refParameterizedConstructor = value -> new ReferenceSource(value);

        final ReferenceSource methodReferenceInstance = refConstructor.get();

        // #2 Ref. to an instance method of a particular object
        final UnaryOperator<String> refInstanceMethodOfParticularObject = methodReferenceInstance::doInstanceMethodOfParticularObject;

        // #3 Ref. to a static method
        final UnaryOperator<String> refStaticMethod = ReferenceSource::doStaticMethod;

        // #4 Ref. to an instance method of an arbitrary object of a particular type
        final Function<ReferenceSource, String> refInstanceMethodOfArbitraryObjectOfParticularType = ReferenceSource::doInstanceMethodOfArbitraryObjectOfParticularType;

        Arrays.stream(new String[] { "a", "b", "c" }).map(refInstanceMethodOfParticularObject).forEach(out::print);
        Arrays.stream(new String[] { "d", "e", "f" }).map(refStaticMethod).forEach(out::print);
        Arrays.stream(new String[] { "g", "h", "i" }).map(refParameterizedConstructor).map(refInstanceMethodOfArbitraryObjectOfParticularType)
                .forEach(out::print);
    }
}

Additionally, you could take a look at this and that thread.

Answer from Oleks on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › methodreferences.html
Method References (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
The following example, MethodReferencesExamples, contains examples of the first three types of method references: import java.util.function.BiFunction; public class MethodReferencesExamples { public static <T> T mergeThings(T a, T b, BiFunction<T, T, T> merger) { return merger.apply(a, b); } public static String appendStrings(String a, String b) { return a + b; } public String appendStrings2(String a, String b) { return a + b; } public static void main(String[] args) { MethodReferencesExamples myApp = new MethodReferencesExamples(); // Calling the method mergeThings with a lambda expression System.out.println(MethodReferencesExamples.
🌐
GeeksforGeeks
geeksforgeeks.org › java › static-method-in-java-with-examples
Static Method in Java With Examples - GeeksforGeeks
A static method in Java is associated with the class, not with any object or instance. It can be accessed by all instances of the class, but it does not rely on any specific instance.
Published   2 weeks ago
Top answer
1 of 3
7

Why it is not allowing AppTest::makeUppercase?

The short answer is that AppTest::makeUppercase isn't valid "reference to an instance method of an arbitrary object of a particular type". AppTest::makeUppercase must implement interface Function<AppTest, String> to be valid reference.

Details:

There are 4 kinds of method references in Java:

  1. ContainingClass::staticMethodName - reference to a static method
  2. containingObject::instanceMethodName - reference to an instance method of a particular object
  3. ContainingType::methodName - reference to an instance method of an arbitrary object of a particular type
  4. ClassName::new - reference to a constructor

Every single kind of method reference requires corresponding Function interface implementation. You use as a parameter the reference to an instance method of an arbitrary object of a particular type. This kind of method reference has no explicit parameter variable in a method reference and requires implementation of the interface Function<ContainingType, String>. In other words, the type of the left operand has to be AppTest to make AppTest::makeUppercase compilable. String::toUpperCase works properly because the type of parameter and type of the instance are the same - String.

import static java.lang.System.out;

import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;

class ReferenceSource {

    private String value;

    public ReferenceSource() {
    }

    public ReferenceSource(String value) {
        this.value = value;
    }

    public String doInstanceMethodOfParticularObject(final String value) {
        return ReferenceSource.toUpperCase(value);
    }

    public static String doStaticMethod(final String value) {
        return ReferenceSource.toUpperCase(value);
    }

    public String doInstanceMethodOfArbitraryObjectOfParticularType() {
        return ReferenceSource.toUpperCase(this.value);
    }

    private static String toUpperCase(final String value) {
        return Optional.ofNullable(value).map(String::toUpperCase).orElse("");
    }
}

public class Main {
    public static void main(String... args) {
        // #1 Ref. to a constructor
        final Supplier<ReferenceSource> refConstructor = ReferenceSource::new;
        final Function<String, ReferenceSource> refParameterizedConstructor = value -> new ReferenceSource(value);

        final ReferenceSource methodReferenceInstance = refConstructor.get();

        // #2 Ref. to an instance method of a particular object
        final UnaryOperator<String> refInstanceMethodOfParticularObject = methodReferenceInstance::doInstanceMethodOfParticularObject;

        // #3 Ref. to a static method
        final UnaryOperator<String> refStaticMethod = ReferenceSource::doStaticMethod;

        // #4 Ref. to an instance method of an arbitrary object of a particular type
        final Function<ReferenceSource, String> refInstanceMethodOfArbitraryObjectOfParticularType = ReferenceSource::doInstanceMethodOfArbitraryObjectOfParticularType;

        Arrays.stream(new String[] { "a", "b", "c" }).map(refInstanceMethodOfParticularObject).forEach(out::print);
        Arrays.stream(new String[] { "d", "e", "f" }).map(refStaticMethod).forEach(out::print);
        Arrays.stream(new String[] { "g", "h", "i" }).map(refParameterizedConstructor).map(refInstanceMethodOfArbitraryObjectOfParticularType)
                .forEach(out::print);
    }
}

Additionally, you could take a look at this and that thread.

2 of 3
1
String::toUpperCase

is short version of

text -> {
    return text.toUpperCase();
}

is again short version of

new Functon<String, String> (String text) {
    Override
    public String apply(String text) {
        return text.toUpperCase();
    }
}

so when you want AppTest::myMethod

you need

public class AppTest {

    public String myMethod(){
        return this.toString();
    }

    public void printFormattedString2(AppTest appTest, Function<AppTest, String> formatter){
        System.out.println(formatter.apply(appTest));
    }

    public static void main(String[] args) {
        AppTest appTest = new AppTest();

        appTest.printFormattedString2(appTest, AppTest::myMethod);
    }
}

because whole version looks so

appTest.printFormattedString2(appTest, new Function<AppTest, String>() {
    @Override
    public String apply(AppTest text) {
        return text.makeUppercase2();
    }
});
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-method-references
Java Method References - GeeksforGeeks
A static method reference is used to refer to a static method of a class. It replaces a lambda expression that simply calls a static method. ... import java.util.*; class MathUtil{ static void square(int n) { System.out.println(n * n); } } class ...
Published   1 month ago
🌐
TutorialsPoint
tutorialspoint.com › reference-to-a-static-method-using-method-references-in-java8
Reference to a static method using method references in ...
August 4, 2020 - In this example, we are referencing the static method of our class to print the elements in three ways. The first approach is a regular approach to print the elements using a for loop. The second approach is to use a lambda expression in a for-each loop. The third approach is using a method reference in a for-each loop to print all the elements. package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String args[]) { List<String> names = new ArrayList<>(); names.add("Mahesh"); names.add("Suresh"); names.add("Ramesh"); names.a
🌐
Baeldung
baeldung.com › home › java › core java › method references in java
Method References in Java | Baeldung
March 26, 2025 - Even though it’s still a one-liner, the method reference is much easier to read and understand. We can reference a constructor in the same way that we referenced a static method in our first example.
🌐
InfoWorld
infoworld.com › home › blogs › java 101: learn java
Get started with method references in Java | InfoWorld
November 12, 2019 - A static method reference refers to a static method in a specific class. Its syntax is className::staticMethodName, where className identifies the class and staticMethodName identifies the static method. An example is Integer::bitCount.
🌐
GeeksforGeeks
geeksforgeeks.org › java › static-methods-vs-instance-methods-in-java
Static Method vs Instance Method in Java - GeeksforGeeks
January 2, 2025 - It requires creating an instance of the class to be called. Can access instance variables, other instance methods, and static members ... import java.io.*; class Test { String n = ""; // Instance method public void test(String n) { this.n = n; } } class Geeks { public static void main(String[] args) { // create an instance of the class Test t = new Test(); // calling an instance method in the class 'Geeks' t.test("GeeksforGeeks"); System.out.println(t.n); } }
Find elsewhere
🌐
Quora
quora.com › What-is-the-reason-static-methods-are-called-by-an-object-reference-instead-of-a-class-name-in-Java
What is the reason static methods are called by an object reference instead of a class name in Java? - Quora
But static methods are shared among all the objects, and whatever manipulation you do in those methods are visible across all objects. So basically, its a conflict of concept. That is why Java warns you of calling static methods with object.
🌐
Great Learning
mygreatlearning.com › blog › it/software development › what is static method in java with examples
What is Static Method in Java with Examples
September 12, 2024 - This method does not need to know anything about the particular file being printed, so it can be declared static. When you use a static method, you refer to the class itself rather than any specific class instance.
Top answer
1 of 2
16

In your example, both the static and the non-static method are applicable for the target type of the filter method. In this case, you can't use a method reference, because the ambiguity can not be resolved. See §15.13.1 Compile-Time Declaration of a Method Reference for details, in particular the following quote and the examples below:

If the first search produces a static method, and no non-static method is applicable [..], then the compile-time declaration is the result of the first search. Otherwise, if no static method is applicable [..], and the second search produces a non-static method, then the compile-time declaration is the result of the second search. Otherwise, there is no compile-time declaration.

In this case, you can use a lambda expression instead of a method reference:

Copya.stream().filter(item -> A.is(item));

The above rule regarding the search for static and non-static methods is somewhat special, because it doesn't matter, which method is the better fit. Even if the static method would take an Object instead of A, it's still ambiguous. For that reason, I recommend as a general guideline: If there are several methods with the same name in a class (including methods inherited from base classes):

  • All methods should have the same access modifiers,
  • All methods should have the same final and abstract modifiers,
  • And all methods should have the same static modifier
2 of 2
-7

We can not use not static methods or non-global methods by using className::methodName notation. If you want to use methods of a particular class you have to have an instance of the class.

CopySo if you want to access is() method then you can use : 
A a = new A();
a.is();
OR 
(new A()).is();

Thanks.

🌐
Tutorialspoint
tutorialspoint.com › java › java_method_references.htm
Java - Method References
In this example, we are referencing the static method of our class to print the elements in three ways. The first approach is a regular approach to print the elements using a for loop. The second approach is to use a lambda expression in a for-each loop. The third approach is using a method reference in a for-each loop to print all the elements. package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class Tester { public static void main(String args[]) { List<String> names = new ArrayList<>(); names.add("Mahesh"); names.add("Suresh"); names.add("Ramesh"); names.a
Top answer
1 of 8
156

Since getText() is non-static you cannot call it from a static method.

To understand why, you have to understand the difference between the two.

Instance (non-static) methods work on objects that are of a particular type (the class). These are created with the new like this:

SomeClass myObject = new SomeClass();

To call an instance method, you call it on the instance (myObject):

myObject.getText(...)

However a static method/field can be called only on the type directly, say like this: The previous statement is not correct. One can also refer to static fields with an object reference like myObject.staticMethod() but this is discouraged because it does not make it clear that they are class variables.

... = SomeClass.final

And the two cannot work together as they operate on different data spaces (instance data and class data)

Let me try and explain. Consider this class (psuedocode):

class Test {
     string somedata = "99";
     string getText() { return somedata; } 
     static string TTT = "0";
}

Now I have the following use case:

Test item1 = new Test();
 item1.somedata = "200";

 Test item2 = new Test();

 Test.TTT = "1";

What are the values?

Well

in item1 TTT = 1 and somedata = 200
in item2 TTT = 1 and somedata = 99

In other words, TTT is a datum that is shared by all the instances of the type. So it make no sense to say

class Test {
         string somedata = "99";
         string getText() { return somedata; } 
  static string TTT = getText(); // error there is is no somedata at this point 
}

So the question is why is TTT static or why is getText() not static?

Remove the static and it should get past this error - but without understanding what your type does it's only a sticking plaster till the next error. What are the requirements of getText() that require it to be non-static?

2 of 8
13

There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String.

A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.

public class NonActivity {

    public static void doStuff(Context context) {
        String TTT = context.getText(R.string.TTT);
        ...
    }
}

And to call this from your Activity:

NonActivity.doStuff(this);

This will allow you to access your String resource without needing to use a public static field.

🌐
Baeldung
baeldung.com › home › java › core java › a guide to the static keyword in java
A Guide to the Static Keyword in Java | Baeldung
January 8, 2024 - As we saw earlier, the JVM loads static variables at class load time, and they belong to the class. On the other hand, we need to create an object to refer to non-static variables. So, the Java compiler complains because there’s a need for an object to call or use non-static variables.
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › method-references-in-java-8
Method References in Java 8
@FunctionalInterface interface MyInterface{ Hello display(String say); } class Hello{ public Hello(String say){ System.out.print(say); } } public class Example { public static void main(String[] args) { //Method reference to a constructor MyInterface ref = Hello::new; ref.display("Hello World!"); } }
🌐
CodingNomads
codingnomads.com › java-method-reference-examples
Java Method Reference Examples
When this happens, the args are automatically passed through the reference without having to write it down manually! The following class represents a Person, and as you can see, it contains a static method - as a reminder, a static method can be called without having to create an instance of the class first.
🌐
Java Almanac
javaalmanac.io › features › method-references
Method References (JSR 335) - javaalmanac.io
The created functional interface instance can be used to invoke the method at a later point in time. Example: import java.util.function.Consumer; class ReferenceExample { public static void main(String[] args) { // Just get the reference Consumer<String> printer = System.out::println; // Now call the method printer.accept("Hello..."); printer.accept("...Reference!"); } }
🌐
Coderanch
coderanch.com › t › 751439 › java › static-reference-static-method
Cannot make a static reference to the non-static method (Beginning Java forum at Coderanch)
May 3, 2022 - It's not an actual language requirement, but it's a standard convention that helps people who read the code. Plus some automated tools get upset when you don't do it that way. A static method cannot reference a member method or property for the simple reason that there are an indeterminate ...