JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Checkout for Promo Codes

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
What is System.out in Java
In System.out, out is an instance of PrintStream. It is a static member variable in System class. This is called standard output stream, connected to console.
Famous Quotations
Success consists of going from failure to failure without loss of enthusiasm.
-- Winston Churchill

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 © 2020 by Nataraja Gootooru. All Rights Reserved.