![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is a casting expression in Java?
A cast expression provides a mechanism to explicitly provide a lambda expression's type if none can be conveniently inferred from context. It is also useful to resolve ambiguity when a method declaration is overloaded with unrelated functional interface types.
Syntax
Object o = () -> { System.out.println("TutorialsPoint"); }; // Illegal: Object o = (Runnable) () -> { System.out.println("TutorialsPoint"); }; // Legal
Example
interface Algebra1 { int operate(int a, int b); } interface Algebra2 { int operate(int a, int b); } public class LambdaCastingTest { public static void main(String[] args) { printResult((Algebra1)(a, b) -> a + b); // Cast Expression in Lambda printResult((Algebra2)(a, b) -> a * b); // Cast Expression in Lambda } static void printResult(Algebra1 a) { System.out.println("From Algebra1 Interface: " + a.operate(40, 20)); } static void printResult(Algebra2 a) { System.out.println("From Algebra2 Interface: " + a.operate(40, 20)); } }
Output
From Algebra1 Interface: 60 From Algebra2 Interface: 800
Advertisements