3

I am not understanding the reason, for having the compilation error for the below program. Where am I going wrong? I want to print the value of the string as output using method reference.

public class ConsumerDemo{
    public static void main(String[] args) {
        test("hello", (str)-> str::toUpperCase);
    }

    public static void test(String str, Consumer<String> consumer) {
        consumer.accept(str);

    }
 }

2 Answers 2

4
test("hello", String::toUpperCase)

should be the correct syntax.

In order to print the upper case of the input, you can use:

String str = "hello"; // any input value
test(str.toUpperCase(), System.out::println);
Sign up to request clarification or add additional context in comments.

3 Comments

I want to print after converting to uppercase
Although this compiles the result of String::toUpperCase will be ignored.
@Aomine agreed that's why wanted to know what OP was willing to perform with the consumer.
3

you cannot combine lambda syntax and method reference syntax as such.

You're either looking for:

test("hello", String::toUpperCase);

or:

test("hello", s -> s.toUpperCase());

but this then means the result of String::toUpperCase/s -> s.toUpperCase() is ignored hence, you'll need to perform something more useful. for example:

test("hello", s -> System.out.println(s.toUpperCase()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.