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
Procedural Vs Object-oriented Programs
In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.

In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.
Famous Quotations
The very best thing you can do for the whole world is to make the most of yourself.
-- Wallace Wattles

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.