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
Default value of a local variables?
The local variables are not initialized to any default values. We should not use local variables with out initialization. Even the java compiler throws error.
Famous Quotations
Discipline is just choosing between what you want now and what you want most.
-- Unknown Author

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.