JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Method Reference - Reference to a Static Method example.


This example shows how to call static methods using Method Reference feature. It is pretty simple and basic example.

package com.java2novice.methodreference;

import java.util.ArrayList;
import java.util.List;

public class StaticMethodReferenceEx {

	public static void main(String a[]) {

		List<String> countryList = new ArrayList<>();
		countryList.add("India");
		countryList.add("USA");
		countryList.add("Japan");
		countryList.add("Canada");

		// print the list elements in normal way
		System.out.println("<--- Prior to java-8 --->");
		for(String str:countryList) {
			StaticMethodReferenceEx.printString(str);
		}

		// In Method Reference way
		System.out.println("\n<--- java-8 method reference way --->");
		countryList.forEach(StaticMethodReferenceEx::printString);

		// in Lambda expression way
		System.out.println("\n<--- java-8 lambda expression way --->");
		countryList.forEach(str -> StaticMethodReferenceEx.printString(str));
	}

	public static void printString(String str) {
		System.out.println(str);
	}
}

Output:
<--- Prior to java-8 --->
India
USA
Japan
Canada

<--- java-8 method reference way --->
India
USA
Japan
Canada

<--- java-8 lambda expression way --->
India
USA
Japan
Canada
 Next Program >>

Java-8 Method References Examples

  1. Method Reference - Reference to a Static Method example.
  2. Method Reference - Reference to a Instance Method example.
  3. Method Reference - Reference to a Constructor example.
Knowledge Centre
StringBuffer Vs StringBuilder
The only difference between StringBuffer and StringBuilder is StringBuffer is thread-safe, that is StringBuffer is synchronized.
Famous Quotations
It’s not that I’m so smart, it’s just that I stay with problems longer.
-- Albert Einstein

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.