Wednesday, March 30, 2022

Interview Question: Sub String Palindrome using java.

Recent day interviews you may faced this question in programing interview. Find the sub string palindrome of given string input.

We have many way to solve it. Here I added coding snippet which I tried to solve it.

First one I used two for loop to solve it. Its very simple and easy.


private static List<String> subStringPalindrome(String value) {
List<String> list = new ArrayList<>();
for(int i =0 ; i < value.length(); i++){
for(int j = i+1 ; j < value.length(); j++){
StringBuffer s1 = new StringBuffer(value.substring(i,j));
String s2 = s1.reverse().toString();
if(value.substring(i,j).contentEquals(s2) && s1.length()> 1){
list.add(s1.toString());
}

}
}
return list;
}
List<String> list = subStringPalindrome("eetestseeammadam");
Output: [ee, ete, estse, sts, ee, amma, mm, ada]
Its very simple and easy. This code look simple and easy  and I tried another way using recursion.

private static List<String> printPalindromeSubString(String value;) {
List<String> list = new ArrayList<>();
if(value.equals(new StringBuilder(value).reverse()))
list.add(value);
for(int i=0; i <= value.length(); i++){
if(i > 1 && i < value.length() -1){
StringBuffer reverse = new StringBuffer(value.substring(i-2, i+1));
if(value.substring(i-2, i+1).contentEquals(reverse.reverse())){
System.out.println("Called2");
list.add(value.substring(i-2, i+1));
if(i>2){
if(i+2 <= value.length()){
new Test().callRecursion(value,value.substring(i-2, i+1), i-1, i, list );
}
}
}
}
if(i > 0 && i < value.length() ){
StringBuffer stringBuffer = new StringBuffer(value.substring(i-1, i+1));
if(value.substring(i-1, i+1).contentEquals(stringBuffer.reverse())){
list.add(value.substring(i-1, i+1));
System.out.println("Called");
if(i > 1){
new Test().callRecursion(value,value.substring(i-1, i+1), i, i, list );
}
}
}
}
return list;
}

private List<String> callRecursion(String value, String reversed, int i, int j, List<String> list){
if(j+1 >= value.length())
return list;
else if(value.charAt(i-2) == value.charAt(j+1)){
String s = value.charAt(i-2) +reversed+ value.charAt(j+1);
list.add(s);

callRecursion(value, s, i-1, j+1, list);
}
System.out.println(list);
return list;
}
List<String> list = printPalindromeSubString("eetestseeammadam");
Here i used recursion to find palindrome on given substring. And the output is 
[ee, ete, sts, estse, ee, mm, amma, ada, madam]

And the output is  If you check the output from two logic, there is a mismatch.. First one print only 8 palindrome and recursion logic print 9 palindrome. 'madam' missing in first logic. 
Lets make this blog more interactive with techies, Please find the missing condition or part of code on comment area.✌✌ 

Thanks in advance.

Wednesday, March 16, 2022

Lambda expression in java.

In this post we will going to discuss about what is lambda expression in java?. How to use them?. How it helps developers?. All this question will be answered end of this post.

Before we start answering this question, let we look in to some implementation to get 10+years experience employee from list of employee object.

Here coding snippet: 


public class Employee {


private int id;
private String name;
private double experience;
private long salary;
private int rating;

public Employee(int id, String name, double experience, long salary, int rating) {
this.id = id;
this.name = name;
this.experience = experience;
this.salary = salary;
this.rating = rating;

    }

    //Getter and Setter here

 }  

Here my implementation class to print 10+years experience employee. 


public static void main(String[] args) {
Employee employee1 = new Employee(5, "Antwaun", 5.5, 10000L, 1);
Employee employee2 = new Employee(2, "Rick", 32.5, 2000L, 3);
Employee employee3 = new Employee(1, "Richard", 50, 3000L, 4);
Employee employee4 = new Employee(3, "Corey", 22.5, 20000L, 2);
Employee employee5 = new Employee(4, "Chumlee", 10.5, 15000L, 5);

List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
employeeList.add(employee4);
employeeList.add(employee5);

printEmployeeExpGreaterTenYears(employeeList);
}
public static void printEmployeeExpGreaterTenYears(List<Employee> employeeList){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10){
System.out.println(employee);
}
}
}

Output:
Employee{id=2, name='Rick', experience=32.5, salary=2000, rating=3}
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=3, name='Corey', experience=22.5, salary=20000, rating=2}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}

This looks good. we are iterating list and check the experience grater or equals to 10. If in future the requirement change like we need to get 10+ experience and rating will be more than 4+. So then we need to change the existing logic or else we need to write a new method with two param. 

Let see the implementation,
public static void printEmployeeExpGreaterTenYearsAndSalaryPassed(
List<Employee> employeeList, int rating){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10 && employee.getRating() >= rating){
System.out.println(employee);
}
}
}

These condition may be change in future. Like employee salary, employee name or we may add some new variable in Employee class. So its not good to change existing logic or add new logic when we have new enhancement to be implement. 
So what else we can do?? .. Let think about Functional Interface in java 8. 
  • Functional interface, which have only one abstract method and any number of default method.
Let we create a Function interface with one abstract method. Interface name CheckEmployee for now have method name test(). 

public interface CheckEmployee {
boolean test(Employee employee);
}

Here we need to implement this test method, so I have created CheckEmployeeService class.
public class CheckEmployeeService implements CheckEmployee {
@Override
public boolean test(Employee employee) {
return (employee.getExperience() >= 10 && employee.getRating() >= 4);
}
}
Let add a method to printEmployee in out Impl class.
public static void printPersons(
List<Employee> employeeList, CheckEmployee checkEmployee){
for(Employee employee: employeeList){
if(checkEmployee.test(employee)){
System.
out.println(employee);
}
}
}
Now we can call this printPersons method from main method, 
printPersons(employeeList, new CheckEmployeeService());
Output:
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}

Its looks good. but we have created a Interface and Service class, that's not necessary we can create them inside the Impl class itself.

As already said CheckPerson interace is Functional interface. Because it has one and only abstract method. Java provide lambda operation for functional interface. We can use lambda expression on functional interface.
Let see how we can use them,

printPersons(employeeList, new CheckEmployeeService());
System.out.println("Lambda expression ");
printPersons(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
Output: 
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}
Lambda expression 
Employee{id=1, name='Richard', experience=50.0, salary=3000, rating=4}
Employee{id=4, name='Chumlee', experience=10.5, salary=15000, rating=5}
Now you might get idea of how do we use lambda expression in java 8. In Functional interface we can use lambda expression. By using lambda expression it reduces the coding effort. Java provide many Functional interface, they all available in java.util.function 
For example we can use you can use the Predicate<T> interface in place of CheckEmployee. This interface contains the method boolean test(T t).
Let see how to use predicate interface instead of CheckEmployee.
public static void printEmployeesWithPredicate(
List<Employee> roster, Predicate<Employee> tester) {
for (Employee p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
call from main method, 
printEmployeesWithPredicate(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
This will print the same output ass like what we have printed by using CheckEmployee interface. So far we have answered what is lambda expression, how to use them and how it helps developer to reduce the coding effort. I hope this will give some basic and deep understanding of lambda expression. 
There are lot of Functional interface we have in java. Please go through the JavaDoc . So When we are speaking about lambda expression you might think of Steams.. Are you??. Okay. Let see how to we use Stream to printPersion.

Classes to support functional-style operations on streams of elements,
such as map-reduce transformations on collections. - JavaDoc .

Stream support functional style operation on stream element. Let we use stream element to printPersons. Here code snippet.
employeeList
.stream()
.filter(
employee -> employee.getExperience() >= 10 && employee.getRating() >= 4)
.forEach(employee -> System.out.println(employee));
This will print the same output ass like what we have printed by using CheckEmployee interface.

I hope this will give some basic and deep understanding of lambda expression and stream.  

Thank you all.
Consolidated Coding snippet.
package com.example.monitoring.lambda;

import com.example.monitoring.compare.CheckEmployee;
import com.example.monitoring.compare.CheckEmployeeService;
import com.example.monitoring.compare.Employee;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class EmployeeServiceImpl {

public static void main(String[] args) {
Employee employee1 = new Employee(5, "Antwaun", 5.5, 10000L, 1);
Employee employee2 = new Employee(2, "Rick", 32.5, 2000L, 3);
Employee employee3 = new Employee(1, "Richard", 50, 3000L, 4);
Employee employee4 = new Employee(3, "Corey", 22.5, 20000L, 2);
Employee employee5 = new Employee(4, "Chumlee", 10.5, 15000L, 5);

List<Employee> employeeList = new ArrayList<>();
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
employeeList.add(employee4);
employeeList.add(employee5);

printEmployeeExpGreaterTenYears(employeeList);
printPersons(employeeList, new CheckEmployeeService());
System.out.println("Lambda expression ");
printPersons(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);
printEmployeesWithPredicate(employeeList,
(Employee employee) -> employee.getExperience() >= 10 && employee.getRating() >= 4);

employeeList
.stream()
.filter(
employee -> employee.getExperience() >= 10 && employee.getRating() >= 4)
.forEach(employee -> System.out.println(employee));
}

public static void printEmployeeExpGreaterTenYears(List<Employee> employeeList){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10){
System.out.println(employee);
}
}
}

public static void printEmployeeExpGreaterTenYearsAndSalaryPassed(
List<Employee> employeeList, int rating){
for(Employee employee: employeeList){
if(employee.getExperience() >= 10 && employee.getRating() >= rating){
System.out.println(employee);
}
}
}
public static void printPersons(
List<Employee> employeeList, CheckEmployee checkEmployee){
for(Employee employee: employeeList){
if(checkEmployee.test(employee)){
System.out.println(employee);
}
}
}

public static void printEmployeesWithPredicate(
List<Employee> roster, Predicate<Employee> tester) {
for (Employee p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}


}

Tuesday, March 1, 2022

Immutable String in Java.

This is very popular interview question in core java interview. Most of us will answer it, String is immutable. When the question is goes why String is immutable, few of us only answer it, due to misunderstanding of immutable.

Here we will discuss about why?.

Immutable is,  once a string object created in string pool or heap we cannot change the value of it. But we can change the value of the reference. That's what we are doing in below code.

String name = "Boomi";
name = "raj";

But we are able to change it right??. Its not what immutable means. Immutable means we cannot edit the "Boomi" from string pool. Let see how above string stored in java memory.

When we create name = "Boomi"value "Boomi" will be create in string pool and assigned this value to name reference.


When we reassign the value "raj" to name. "raj" value will be created in string pool and this value is referred to name variable. But still "Boomi" value is there in string pool and reference to name is removed. This is why string is called immutable.

Now you may have a question why java engineers made string as immutable. 

Let see an example to understand why string immutable? 

String name = "Boomi";
String userName = "Boomi";

Here we are creating two string with same name. If String is mutable then we need to create two time value "Boomi". So it might consume lot of memory for real time application. 

Another reason for String immutability is security. 


Let change name value to "Boomiraj".

name = "Boomiraj";



New Object will be created for "Boomiraj" this referred to name variable. userName still referring to the "Boomi".

We know we can create String object two ways, 

  • by using "". eg String name = "Boomi"; //Object stored in string pool
  • by using new. eg String userName = new String("Boomi");//Object stored in heap memory.
String name = "Boomi";
String userName = "Boomiraj";
String nameObj = new String("Boomi");
String userNameObj = new String("Boomiraj");




Let check the both name and userName not pointing to same object by using ==

System.out.println(name == nameObj); //false
System.out.println(userName == userNameObj);//false

Null Pointer Exception in Java

Here we will discuss about what is nullpointerexception and how to fix it?

In java if a variable or object reference do not have any value to assign to them , then we will have possibility of having null pointer exception. More clearly if a reference variable or object is assigned to nothing. For example,

public class NullPointerException {
public static void main(String[] args) {
Employee employee = null;
employee.getName();
}
}

Lets run this program, we are getting exception says below.,

Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:8)
Here we are trying to call getName() of employee object, but we did not create a object for it.  Which mean employee is referred to nothing . 

How to fix this issue, we need to create a new employee object using new Employee().After changing null to this we will not get exception. We are not assigned any value to employee name variable, even we don't get any exception, because we have not call any further from getName(). Let me modified something from above example,

public class NullPointerException {
public static void main(String[] args) {
Employee employee = new Employee();
employee.getName().length();
}
}

While running the main method we will get below exception
Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:8).

How to fix this issue, before we fix it, let we check other possible ways of having null pointer exception.

public class NullPointerException {
public static void main(String[] args) {
List<Employee> employeeList = null;
for(Employee employee1 : employeeList){
System.out.println(employee1);
}
}
}
Here we will get nullpointerexception on for loop, because we are trying to iterate from nothing.

List<Employee> employeeList = null;
Employee employee = new Employee();
employeeList.add(employee);
for(Employee employee1 : employeeList){
if(employee1.getName().equals("Boomiraj")){
System.out.println("Hello Boomiraj");
}
}

We will get exception on if condition to check equals(), because we do not set name to the employee object, so employee1 will have null on name variable. 

public static void main(String[] args) {
Employee employee = new Employee();
getEmployeeNameLength(employee);
}

public static int getEmployeeNameLength(Employee employee){
return employee.getName().length();
}

Here we will get exception on return statement of getEmployeeNameLength , here the exception trace will be like this and more details on it, 


Exception in thread "main" java.lang.NullPointerException
at com.example.monitoring.exception.NullPointerException.getEmployeeNameLength(NullPointerException.java:15)
at com.example.monitoring.exception.NullPointerException.main(NullPointerException.java:11)

We have seen all the possible ways of having nullpointerexception. Let see how to fix them.

Never assign object reference to null, just initialize them new Employee();. We may have some scenarios to have dynamic object, there we cannot initialize object. we can handle them with condition check using null. let see above code we are trying to get length of the name from employee object. 

We need to check the getName is null or not before we call .length(). Before call getName() we need to check employee object itself null or not.

public static int getEmployeeNameLength(Employee employee){
if(employee != null &&
employee.getName() != null)
{
return employee.getName().length();
}
return 0;
}
Above code might be looks like ugly code, we don't have any other option to check it.

On employee name equals check we need to pass static value first then we need to check equality.

if("Boomiraj".equals(employee.getName())){
System.out.println("Hello Boomiraj");
}

For loop fix we need initialize the list object.
List<Employee> employeeList = new ArrayList<>();

Now we have fixed all the possible ways of null exception. 

But this could not be happen to primitive type. Because we cannot declare a primitive type as null, primitive types always have their default value. Lets try with example.

Boolean isNull = null;
if(isNull){
System.out.println("Its null!");
}
 Lets try with example. Here I used Boolean wrapper class. So we can assign null to it, but if we use primitive boolean we cannot assign null to it. 

boolean isNull = null; 
Here I am getting compilation error says, required type boolean, provider null.
If you have possible way to declare primitive type, use them to rid out of nullpointerexception.

Thank you!.