What is a Lambda expression in Java ?
A Lambda expression represents an Anonymous method.
Anonymous method concept is similar to that of an Anonymous class… the difference being it implements a functional interface.
Functional interface is a new interface concept in Java 8. A functional interface can only declare one abstract method.
Lambda expressions allow the programmer to pass code in a concise manner making the code more clearer and flexible.
Lambda syntax
A lambda expression contains:
A parameter list
An arrow symbol(->)
Body of the lambda containing statements
The syntax for Lambda expressions is:
(parameters) -> {statements;}
How to write simple methods as lambda expression
Here is a simple method that displays a message “Hello World”.
1
2
3
4
5
public void hello(){
System.out.println("Hello World");
}
To convert this method to a lambda expression, remove the access specifier “public”, return type “void” and method name “hello” and write it as :
1
2
3
() -> {System.out.println("Hello World");}
Here is another method example that adds two numbers and returns their sum :
1
2
3
4
5
int add(int x, int y){
return x+y;
}
This method can be converted to lambda expression as :
1
2
3
(int x, int y) -> {return x+y;}
Important points about lambda expressions
Here are some notable points regarding lambda expressions :
1 ) A lambda expression can have zero or more parameters.
Here is an example of lambda expression with zero parameters:
1
2
3
() -> {System.out.println("Hello World");}
Here is an example of lambda expression with two parameters:
1
2
3
(int x, int y) -> {return x+y;}
This lambda expression accepts two integer parameters and returns their sum.
2) If the type of the parameters can be decided by the compiler, then we can ignore adding them in the lambda expression.
1
2
3
4
5
(int x, int y) -> {return x+y;} // type mentioned
(x,y) -> {return x+y;}; // type ingored
3) If there is only one parameter, the parenthesis of parameter can be omitted.
Here are some examples :
1
2
3
4
5
6
7
x -> {return x+10;}
String s -> s.toUpperCase()
String s -> System.out.println(s)
4) If the body has just one expression, the return keyword and curly braces can be omitted as show below:
1
2
3
(int x, int y) -> x + y
If the return type of parameters is omitted, the compiler determines default parameter types.
1
2
3
4
5
(x,y) -> x+y
(str, i) -> str.substring(i)
5) A lambda can also have empty parameters
1
2
3
4
5
() -> {return “Hello”;}
() -> System.out.println(“Hello”)
6) A lambda can also have empty parameter as well as empty body
1
2
3
() -> {}
This represents a valid lambda expression that takes no parameters and returns void.
How to call a lambda expression ?
Once a lambda expression is written, it can be called and executed like a method.
For calling a lambda expression, we should create a functional interface.
Here is an example that uses functional interface to execute lambda expression :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class FuntionalInterfaceDemo {
interface MyInter{
void hello();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyInter infVar = () -> {System.out.println("Hello World");};
infVar.hello();
}
}
Refer more details on functional interface and executing lambda expressions in the following article:
Running lambda expression with Functional Interface
A Lambda expression represents an Anonymous method.
Anonymous method concept is similar to that of an Anonymous class… the difference being it implements a functional interface.
Functional interface is a new interface concept in Java 8. A functional interface can only declare one abstract method.
Lambda expressions allow the programmer to pass code in a concise manner making the code more clearer and flexible.
Lambda syntax
A lambda expression contains:
A parameter list
An arrow symbol(->)
Body of the lambda containing statements
The syntax for Lambda expressions is:
(parameters) -> {statements;}
How to write simple methods as lambda expression
Here is a simple method that displays a message “Hello World”.
1
2
3
4
5
public void hello(){
System.out.println("Hello World");
}
To convert this method to a lambda expression, remove the access specifier “public”, return type “void” and method name “hello” and write it as :
1
2
3
() -> {System.out.println("Hello World");}
Here is another method example that adds two numbers and returns their sum :
1
2
3
4
5
int add(int x, int y){
return x+y;
}
This method can be converted to lambda expression as :
1
2
3
(int x, int y) -> {return x+y;}
Important points about lambda expressions
Here are some notable points regarding lambda expressions :
1 ) A lambda expression can have zero or more parameters.
Here is an example of lambda expression with zero parameters:
1
2
3
() -> {System.out.println("Hello World");}
Here is an example of lambda expression with two parameters:
1
2
3
(int x, int y) -> {return x+y;}
This lambda expression accepts two integer parameters and returns their sum.
2) If the type of the parameters can be decided by the compiler, then we can ignore adding them in the lambda expression.
1
2
3
4
5
(int x, int y) -> {return x+y;} // type mentioned
(x,y) -> {return x+y;}; // type ingored
3) If there is only one parameter, the parenthesis of parameter can be omitted.
Here are some examples :
1
2
3
4
5
6
7
x -> {return x+10;}
String s -> s.toUpperCase()
String s -> System.out.println(s)
4) If the body has just one expression, the return keyword and curly braces can be omitted as show below:
1
2
3
(int x, int y) -> x + y
If the return type of parameters is omitted, the compiler determines default parameter types.
1
2
3
4
5
(x,y) -> x+y
(str, i) -> str.substring(i)
5) A lambda can also have empty parameters
1
2
3
4
5
() -> {return “Hello”;}
() -> System.out.println(“Hello”)
6) A lambda can also have empty parameter as well as empty body
1
2
3
() -> {}
This represents a valid lambda expression that takes no parameters and returns void.
How to call a lambda expression ?
Once a lambda expression is written, it can be called and executed like a method.
For calling a lambda expression, we should create a functional interface.
Here is an example that uses functional interface to execute lambda expression :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class FuntionalInterfaceDemo {
interface MyInter{
void hello();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyInter infVar = () -> {System.out.println("Hello World");};
infVar.hello();
}
}
Refer more details on functional interface and executing lambda expressions in the following article:
Running lambda expression with Functional Interface
❤1👍1
import java.util.Arrays;
import java.util.LinkedHashSet;
public class ArrayExample
{
public static void main(String[] args) throws CloneNotSupportedException
{
//Array with duplicate elements
Integer[] numbers = new Integer[] {1,2,3,4,5,1,3,5};
//This array has duplicate elements
System.out.println( Arrays.toString(numbers) );
//Create set from array elements
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>( Arrays.asList(numbers) );
//Get back the array without duplicates
Integer[] numbersWithoutDuplicates = linkedHashSet.toArray(new Integer[] {});
//Verify the array content
System.out.println( Arrays.toString(numbersWithoutDuplicates) );
}
}
https://cjavapoint.blogspot.com/?m=1
import java.util.LinkedHashSet;
public class ArrayExample
{
public static void main(String[] args) throws CloneNotSupportedException
{
//Array with duplicate elements
Integer[] numbers = new Integer[] {1,2,3,4,5,1,3,5};
//This array has duplicate elements
System.out.println( Arrays.toString(numbers) );
//Create set from array elements
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>( Arrays.asList(numbers) );
//Get back the array without duplicates
Integer[] numbersWithoutDuplicates = linkedHashSet.toArray(new Integer[] {});
//Verify the array content
System.out.println( Arrays.toString(numbersWithoutDuplicates) );
}
}
https://cjavapoint.blogspot.com/?m=1
Blogspot
Core Java Interview Questions - Learn Java
Java Tutorial or Learn Java or Core Java Tutorial or Java Programming Tutorials for beginners and professionals with core concepts and examples
Armstrong Number in Java
In this section, we will discuss what is Armstrong number and also create Java programs to check if the given number is an Armstrong number or not. The Armstrong number program frequently asked in Java coding interviews and academics.
Armstrong Number
An Armstrong number is a positive m-digit number that is equal to the sum of the mth powers of their digits. It is also known as pluperfect, or Plus Perfect, or Narcissistic number. It is an OEIS sequence A005188. Let’s understand it through an example.
https://cjavapoint.blogspot.com/?m=1
In this section, we will discuss what is Armstrong number and also create Java programs to check if the given number is an Armstrong number or not. The Armstrong number program frequently asked in Java coding interviews and academics.
Armstrong Number
An Armstrong number is a positive m-digit number that is equal to the sum of the mth powers of their digits. It is also known as pluperfect, or Plus Perfect, or Narcissistic number. It is an OEIS sequence A005188. Let’s understand it through an example.
https://cjavapoint.blogspot.com/?m=1
Blogspot
Core Java Interview Questions - Learn Java
Java Tutorial or Learn Java or Core Java Tutorial or Java Programming Tutorials for beginners and professionals with core concepts and examples
11 = 1
2: 21 = 2
3: 31 = 3
153: 13 + 53 + 33 = 1 + 125+ 27 = 153
125: 13 + 23 + 53 = 1 + 8 + 125 = 134 (Not an Armstrong Number)
2: 21 = 2
3: 31 = 3
153: 13 + 53 + 33 = 1 + 125+ 27 = 153
125: 13 + 23 + 53 = 1 + 8 + 125 = 134 (Not an Armstrong Number)
import java.util.Scanner;
import java.lang.Math;
public class ArmstsrongNumberExample
{
//function to check if the number is Armstrong or not
static boolean isArmstrong(int n)
{
int temp, digits=0, last=0, sum=0;
//assigning n into a temp variable
temp=n;
//loop execute until the condition becomes false
while(temp>0)
{
temp = temp/10;
digits++;
}
temp = n;
while(temp>0)
{
//determines the last digit from the number
last = temp % 10;
//calculates the power of a number up to digit times and add the resultant to the sum variable
sum += (Math.pow(last, digits));
//removes the last digit
temp = temp/10;
}
//compares the sum with n
if(n==sum)
//returns if sum and n are equal
return true;
//returns false if sum and n are not equal
else return false;
}
//driver code
public static void main(String args[])
{
int num;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the limit: ");
//reads the limit from the user
num=sc.nextInt();
System.out.println("Armstrong Number up to "+ num + " are: ");
for(int i=0; i<=num; i++)
//function calling
if(isArmstrong(i))
//prints the armstrong numbers
System.out.print(i+ ", ");
}
}
https://cjavapoint.blogspot.com/?m=1
import java.lang.Math;
public class ArmstsrongNumberExample
{
//function to check if the number is Armstrong or not
static boolean isArmstrong(int n)
{
int temp, digits=0, last=0, sum=0;
//assigning n into a temp variable
temp=n;
//loop execute until the condition becomes false
while(temp>0)
{
temp = temp/10;
digits++;
}
temp = n;
while(temp>0)
{
//determines the last digit from the number
last = temp % 10;
//calculates the power of a number up to digit times and add the resultant to the sum variable
sum += (Math.pow(last, digits));
//removes the last digit
temp = temp/10;
}
//compares the sum with n
if(n==sum)
//returns if sum and n are equal
return true;
//returns false if sum and n are not equal
else return false;
}
//driver code
public static void main(String args[])
{
int num;
Scanner sc= new Scanner(System.in);
System.out.print("Enter the limit: ");
//reads the limit from the user
num=sc.nextInt();
System.out.println("Armstrong Number up to "+ num + " are: ");
for(int i=0; i<=num; i++)
//function calling
if(isArmstrong(i))
//prints the armstrong numbers
System.out.print(i+ ", ");
}
}
https://cjavapoint.blogspot.com/?m=1
Blogspot
Core Java Interview Questions - Learn Java
Java Tutorial or Learn Java or Core Java Tutorial or Java Programming Tutorials for beginners and professionals with core concepts and examples
👍1
Static Blank Final Variable In Java
In java, static blank final variable is a variable which is declared with final keyword but not initialised at declaration time. It can only be initialised in static block.
https://cjavapoint.blogspot.com/?m=1
In java, static blank final variable is a variable which is declared with final keyword but not initialised at declaration time. It can only be initialised in static block.
https://cjavapoint.blogspot.com/?m=1
Blogspot
Core Java Interview Questions - Learn Java
Java Tutorial or Learn Java or Core Java Tutorial or Java Programming Tutorials for beginners and professionals with core concepts and examples
Throw And Throws In Java
throw:
throw is used in re-throwing exception process or we can say that it is used to throw an exception object explicitly. It can take at most one argument which will be an exception object. Only unchecked exception can be thrown.
throws:
throws keyword is used to throw an exception object implicitly. The throws keyword is used with the method signature. We can declare more than one type of exceptions with method signature which should be comma separated.
Note:
1. throws is commonly used to throw checked exception.
2. If we are calling a method that declares an exception then we must have to either caught or declare the exception.
3. Exception can be re-thrown.
https://cjavapoint.blogspot.com/?m=1
throw:
throw is used in re-throwing exception process or we can say that it is used to throw an exception object explicitly. It can take at most one argument which will be an exception object. Only unchecked exception can be thrown.
throws:
throws keyword is used to throw an exception object implicitly. The throws keyword is used with the method signature. We can declare more than one type of exceptions with method signature which should be comma separated.
Note:
1. throws is commonly used to throw checked exception.
2. If we are calling a method that declares an exception then we must have to either caught or declare the exception.
3. Exception can be re-thrown.
https://cjavapoint.blogspot.com/?m=1
Blogspot
Core Java Interview Questions - Learn Java
Java Tutorial or Learn Java or Core Java Tutorial or Java Programming Tutorials for beginners and professionals with core concepts and examples