Friday, April 22, 2022

Coding interview questions: Python

Hello, 

Here in this post I will solve some basic coding interview question. This time I used python. Yes its cool.

Find second largest number in given array?

input: [1,2,0,9,8] output: 8
input: [0,1,-1,-2] output: 0
input: [3] output: 
input: [] output: 
def findSecondLargestNumber(arr_list):
  largest = None
  secondL = None
  for i in arr_list:
    if largest == None:
      largest = i
    elif i > largest:
      secondL = largest
      largest = i
    elif secondL == None:
      secondL = i
    elif i > secondL:
      secondL = i
    
  print(secondL)

findSecondLargestNumber([0-11])

Find given two string inputs are reverse?
input: "ABC", "CBA" Output : True
input: "ABC", "cBA" Output : False
input: "ABC", "BCA" Ouput: False

def stringReverse(string1string2):
  for i in range(len(string1)):
    i1 = len(string2) - i -1;
    if(string1[i] != string2[i1]):
      return False
  return True 

stringReverse('ABC''cba')

Find given two string number, first input is greater than 2nd without using (int) convert?

Input: "1234" "4321" Ouput: False
Input: "1234" "321" Ouput: True
Input: "1234" "1234" Ouput: False

def largerthan(str1str2):
  if(len(str1) == len(str2)):
    for i in range(len(str1)):
      if str1[i] == str2[i]:
        continue
      elif str1[i] > str2[i]:
        return True
      else:
        return False
    return False
  elif len(str1) > len(str2):
    return True
  else:
    return False

largerthan('723''234')

Find rooks are safe in chessboard, if u don't know what is that? Don't worry, in chessboard rook can move vertical and horizontal line, if any rook block this we then moving rook will kill that?

For testing purpose I am using 4*4 board input instead of 8*8
Input: [[1,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,1]] Output: True
Input: [[1,0,0,0],[0,1,0,0],[0,1,0,0],[0,0,0,1]] Output: False (because array[1,1] and array[2,1] are in same vertical line,
so the rooks are not safe)

def rookSafe(arr):
  for i in range(len(arr)):
    countRow = 0;
    countCol = 0;
    for j in range(len(arr)):
      countRow += arr[i][j]
      countCol += arr[j][i]
      if countCol > 1 or countRow > 1:
        return False
  return True

rookSafe([[1,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,0,1]])


Java solution will be post soon!!👀

Thank you.

Thursday, April 21, 2022

Error: The Angular Compiler requires TypeScript 4.2.3 and 4.4.0 but 4.6.3 was found instead.

After resolve this error, ng serve brings up new error.


Error: The Angular Compiler requires TypeScript >=4.2.3 and <4.4.0 but 4.6.3 was found instead.


So again version mismatch, but this time error it self it clear so I easily fixed this error like pro.

Again I changed typescript version  from "typescript""^4.3.5" to "typescript""4.3.5".

changed What happen when we have while doing npm install angular finds most recent version of typescript, in package-lock.json "typescript""4.6.3" is got update. so I have change "typescript""4.3.5" in package.json.

This solved my issue. 


Conclusion: If you face any weird error from core/webpack or any check your typescript and angular version between package.json and package-lock.json so that we can find between what you expected to load to build and what angular try to find.

Error: Error on worker #1: TypeError: ts.isNamedTupleMember is not a function

While trying to run ng serve on my angular project I got below error,

- Generating browser application bundles (phase: setup)...Compiling @angular/core : es2015 as esm2015
Error: Error on worker #1: TypeError: ts.isNamedTupleMember is not a function
    at StaticInterpreter.visitType (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:699:25)
    at StaticInterpreter.visitVariableDeclaration (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:303:46)
    at StaticInterpreter.visitDeclaration (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:264:29)
    at StaticInterpreter.visitAmbiguousDeclaration (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:372:22)
    at StaticInterpreter.visitIdentifier (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:242:31)
    at StaticInterpreter.visitExpression (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:99:31)
    at StaticInterpreter.visitPropertyAccessExpression (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:342
:28)
    at StaticInterpreter.visitExpression (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:102:31)
    at StaticInterpreter.visitCallExpression (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:431:28)
    at StaticInterpreter.visitExpression (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\src\ngtsc\partial_evaluator\src\interpreter.js:105:31)
    at ClusterMaster.onWorkerMessage (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\ngcc\src\execution\cluster\master.js:195:27)
    at C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\ngcc\src\execution\cluster\master.js:55:95
    at ClusterMaster.<anonymous> (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\ngcc\src\execution\cluster\master.js:293:57)
    at step (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\node_modules\tslib\tslib.js:143:27)
    at Object.next (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\node_modules\tslib\tslib.js:124:57)
    at C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\node_modules\tslib\tslib.js:117:75
    at new Promise (<anonymous>)
    at Object.__awaiter (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\node_modules\tslib\tslib.js:113:16)
    at EventEmitter.<anonymous> (C:\Workspace\SPRINGBOOT\untitled\node_modules\@angular\compiler-cli\ngcc\src\execution\cluster\master.js:287:32)
    at EventEmitter.emit (events.js:314:20)
C:\Workspace\SPRINGBOOT\untitled\node_modules\@ngtools\webpack\src\ngcc_processor.js:139
            throw new Error(errorMessage + `NGCC failed${errorMessage ? ', see above' : ''}.`);
            ^
Error: NGCC failed.
    at NgccProcessor.process (C:\Workspace\SPRINGBOOT\untitled\node_modules\@ngtools\webpack\src\ngcc_processor.js:139:19)
    at C:\Workspace\SPRINGBOOT\untitled\node_modules\@ngtools\webpack\src\ivy\plugin.js:129:27
    at Hook.eval [as call] (eval at create (C:\Workspace\SPRINGBOOT\untitled\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:26:1)
    at Hook.CALL_DELEGATE [as _call] (C:\Workspace\SPRINGBOOT\untitled\node_modules\tapable\lib\Hook.js:14:14)
    at Compiler.newCompilation (C:\Workspace\SPRINGBOOT\untitled\node_modules\webpack\lib\Compiler.js:1043:30)
    at C:\Workspace\SPRINGBOOT\untitled\node_modules\webpack\lib\Compiler.js:1088:29
    at Hook.eval [as callAsync] (eval at create (C:\Workspace\SPRINGBOOT\untitled\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:20:1)
    at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Workspace\SPRINGBOOT\untitled\node_modules\tapable\lib\Hook.js:18:14)
    at Compiler.compile (C:\Workspace\SPRINGBOOT\untitled\node_modules\webpack\lib\Compiler.js:1083:28)
    at C:\Workspace\SPRINGBOOT\untitled\node_modules\webpack\lib\Watching.js:200:19
C:\Workspace\SPRINGBOOT\untitled>ng serve --fix
Unknown option: '--fix'


After spending lot of time on 'npm cache clean --fix' and deleting node_module, we have find that typescript version is creating problem here. So I upgrade my "typescript""3.6.5" to "typescript""^4.3.5"

This solved my issue. 

After that I run ng serve. There I got new error. 


Thank you!. 

Tuesday, April 19, 2022

java.lang.IllegalArgumentException: Not a managed type: class com.example.demo.entity.Customer

I tried to add couple of new entity classes in my project, service implementation and repository for those entity. Once after all done I tried to run my application, my IDE show up to below exception to me.


"org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepo' defined in com.example.demo.repo.CustomerRepo defined in @EnableJpaRepositories declared on DemoApplication: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.demo.entity.Customer"

Here my Repo and Customer class

public interface CustomerRepo extends JpaRepository<Customer, Integer> {
}
public class Customer {
private Integer id;
private String name;
private String mobile;
private String email;
}

Its clearly says Customer class is not able to manage by JpaRepository. So JPA not able to consider this Customer class as entity. Because I used Customer class in Repo class as JpaRepository. 

Here the mistake is I forget to change the POJO to Entity. I missed to annotate Customer class with @Entity.


@Entity
@Table(name= "customer", schema = "public")
public class Customer {

So we need to add @Entity annotation to tell jpa this is a entity class to resolve 
this error.

This solve the above exception.

Machine learning key terms basics

ML - Key terms 

-> Classification - Identify a group/category from bunch of test data with given input data
-> To Classify a input we need to train a machine with algorithm with test data - training set
-> training set have N no of feature and one target variable
-> target variable is what we are trying to predict with ML algorithm.

-> In training set data target variable is known. 
-> Machine learn to find the relationship between feature and target variable - target variable is also known as class
-> To train a ML algorithm we need training data(X axis) and test data(Y axis)
-> To find desired level of accuracy is called knowledge representation
-> Regression is prediction of a numeric value
-> Classification and Regression is supervised learning

-> Non-supervised learning -> clustering - is a task where we group similar items
-> Non-supervised learning we will not have target value on data set.
-> Non-supervised learning reduce the data from many feature into smaller number of data, so we can visualize 2D or 3D format(eg: chart)
-> we need to find statical value that described data -> destiny estimation
-> training steps is not needed here because we will not have target value to train a machine.

-> Supervised learning - trying to predict the target value
-> if your target value is Yes/No or 1/2/3 or True/False this is called classification
-> if your target value is number of values like 0.00 to 100.00 or -9 to +9 is called regression 
-> Non-supervised learning - trying to find group for given data
    -> If you are trying to find group for given data is called clustering
-> If you need some numerical estimate to how strong the fit with each group , this is called Destiney estimation algorithm

-> To make better ML application we need to spend quality of time with data set. 

-> Steps of ML algorithm
-> create data
-> prepare input data
-> analyze input data
-> train the algorithm - Non-supervised does not required this steps
-> test algorithm
-> use it


-> Knn algorithm used to classify the data..  

continue in upcoming post...

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

 I have faced "

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured" error while setting up my learning project using spring boot with postgres.


After spending an hour on searching to fix this issue I have found the solution for it.

Adding below in application.properties resolve this issue for me.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

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!.