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);
 }
 }
Naman
32.8k32 gold badges240 silver badges385 bronze badges
asked Oct 19, 2018 at 17:37

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);
answered Oct 19, 2018 at 17:39
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()));
answered Oct 19, 2018 at 17:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.