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
What is race condition?
A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked.
Famous Quotations
Good judgment comes from experience, and experience comes from bad judgment.
-- Barry LePatner

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.