Saturday, June 17, 2017

Program to find whether the Book is on Public link or not

In this post we will try to understand whether the book is on public link or not.
First question someone ask would be , What is meant by public link ??

PUBLIC LINK- Public link is referred as the links where all the contents are free to use , there is no copy right problem if we use the content of the website.

Objective: I have got the problem where we need to check whether the Book with particular ISBN is present on public link or not.
To check that , we first know the public links are , so few are (which i am checking ) -
https://archive.org/
googlebooks
https://www.gutenberg.org/


Problem- User will provide one isbn number and we need to return whether the isbn is presented on public link or not.

Solution approach- We will provide the api where the user will provide the isbn and we will return the true or false.

Internally , we are using the rest api which will connect with the mentioned public link and provide us where the book is on these site or not using the isbn no.


you can get the Project from here- 
https://github.com/visparashar/ISDNDemo

You can contribute on this project , if you guys have some good idea.

Hope you learn something new. BTW this task i have completed and got some money from freelancer.com

Want to become freelancer .JOIN HERE

Tuesday, February 7, 2017

Garbage Collector and its Algorithms - JAVA

-------------------Garbage Collection-----------------------
In java , programmer need not to care about the objects which are no longer in use. garbage collector
destroy those objects and make the memory available for the programmer to use again.
- garbage collector not guaranteed to run at any specific time.
there are few method of garbage collector



------------The finalize () method:
Called by the garbage collector on an object when garbage collector determines that there are no more references to the object
Note :

The finalize method is never invoked more than once by a Java virtual machine for any given object.
Our program must not rely on the finalize method because we never know if finalize will be executed or not.

----------------gc() – request to JVM

We can request to run the garbage collector using java.lang.System.gc() but it does not force garbage collection, the JVM will run garbage collection only when it wants to run it.­­
We may use system.gc() or runtime.gc()
import java.lang.*;
public class Test
{
    public static void main(String[] args)
    {
        int g1[] = { 0, 1, 2, 3, 4, 5 };
        System.out.println(g1[1] + " ");

        // Requesting Garbage Collector
        System.gc();
        System.out.println("Hey I just requested "+
                          "for Garbage Collection");
    }
}

--------What happens when group of object only refer to each other?

It is possible that a set of unused objects only refer to each other.
This is also referred as Island of Isolation.
For example, object o1 refers to object o2. Object o2 refers to o1. None of them is referenced by any other object.
In this case both the objects o1 and o2 are eligible for garbage collection.


-------------------ALGORITHM USED BY Garbage Collector to remove objects.
Garbage Collector uses 2 alogrithm to remove objects

* Mark and sweep Algorithm
* Island of isolation


-------------------Mark and sweep alogrithm-------------
The main activity of garbage collector is to first identify the unused objects and them claim the head memory to available for use.
There are 2 phase to perform in marks and sweep alogrithm-
1) mark phase
2) sweep phase

In Mark Phase , whenever any object is created its mark bit is set to be false (0) , so in mark phase we set all the reachable object marked bit as true(1),
to perfome is operation , we simply do graph traversal , deepth first search in particular, here we consider all objects as nodes ,and all the nodes connected to one nodes are visited and set as true.

Root is a variable that refer to an object and is directly accessible by local variable. We will assume that we have one root only.
We can access the mark bit for an object by: markedBit(obj).

In Sweep Phase : In sweep phase , all the unreachable objects are sweeped , i.e all the objects whose marked bits are false , will be remove heap memory.
and then the marked bit of all the reachable object will again sets as false , so that they will be again available to recurring process.


------------Island of Isolation -----------------------

Object 1 references Object 2 and Object 2 references Object 1. Neither Object 1 nor Object 2 is referenced by any other object. That’s an island of isolation.
Basically, an island of isolation is a group of objects that reference each other but they are not referenced by any active object in the application. Strictly speaking, even a single unreferenced object is an island of isolation too.

Design Pattern

Design Pattern
-----------------
* Creatational Design Pattern- the way to create object.
used when we need to make decision for creating the instance of class.
Type-
1) Factory Design pattern- It says that let create the abstract class or interface for creating an object but let the subclass decide which class to instanciated.
 * also known as virtual constructor

 Ex -

 package inv.learning.designpattern;


interface Animal{

String name="";
String getType();

}
class Dog implements Animal{

@Override
public String getType() {
// TODO Auto-generated method stub
return "Dog";

}

}
class Cat implements Animal{

@Override
public String getType() {
// TODO Auto-generated method stub
return "Cat";

}

}

class AnimalFactory{

static Animal getAnimal(String str){
if(str==null)
return null;
else if (str.equalsIgnoreCase("CAT"))
return new Cat();
else if (str.equalsIgnoreCase("DOG"))
return new Dog();
else
return null;
}

}
public class FactoryDesign {

public static void main(String[] args) {
// AnimalFactory factory = new AnimalFactory();
Animal dog = AnimalFactory
.getAnimal("Cat");
System.out.println(dog.getType());
Animal cat= AnimalFactory.getAnimal("DOG");
System.out.println(cat.getType());
}

}

------------------------------------------------------------------------------------------------------
2) Abstract Factory Pattern-define an interface or abstract class for creating families of related (or dependent) objects but without specifying their concrete sub-classes.



-------------------
3) Singleton Design pattern- define a class which only have one instance and provides a global  point of  access to it.

Ex -
public class Singleton {

public static void main(String[] args) {
MySingletonClass temp=MySingletonClass.getInstance();


}

}
class MySingletonClass {

private final static MySingletonClass myclass=null;
private MySingletonClass(){}
static MySingletonClass getInstance(){
if(myclass == null)
return new MySingletonClass();
else
return myclass;

}
}

----------------------------
3) Prototype design pattern- cloning of an existing object instead of creating new one and can also be customized as per the requirement.
we use this pattern when creating object is expensinve.
t reduces the need of sub-classing.
It hides complexities of creating objects.
The clients can get new objects without knowing which type of object it will be.
It lets you add or remove objects at runtime.

Example-

public class Prototype {
public static void main(String[] args) {
Employee emp= new Employee(10, "vishal", "g4s");
System.out.println("address of first emp object "+emp.address);
Employee emp2=(Employee)emp.getClone();
System.out.println("address of sec emp object "+emp2.address);
}
}
interface InfPrototype{
InfPrototype getClone();
}
class Employee implements InfPrototype
{ int age;
String name;
public String address;

public Employee(){

}
public Employee(int age,String name,String address)
{
this.age=age;
this.name=name;
this.address=address;
}
@Override
public InfPrototype getClone() {
// TODO Auto-generated method stub
return new Employee(age,name,address);
}

}
--------------------------------
4) Builder Design Pattern-  wehen we construct a complex object from simple object using step by step approach.
It provides clear separation between the construction and representation of an object.
It provides better control over construction process.
It supports to change the internal representation of objects.


-----------------------------------------------------------------------------------------------------------------------
STRUCTURAL DESIGN Pattern-simplifies the structure by identifying the relationships

1) Adapter Design Pattern- converts the interface of a class into another interface that a client wants
 it is also known as wrapper.
 When an object needs to utilize an existing class with an incompatible interface.
When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.
When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.



2)Bridge Pattern-Decouple the functional abstraction from the implementation so that the two can vary independently
The Bridge Pattern is also known as Handle or Body.

When you don't want a permanent binding between the functional abstraction and its implementation.
When both the functional abstraction and its implementation need to extended using sub-classes.
It is mostly used in those places where changes are made in the implementation does not affect the clients.

Thanks for reading
-Noeik

Breadth first Traversal(BFT) AND Depth First Traversal(DST) Program in java

Hello Guys , Hope you all are doing good , so today we are going to see the BST and DST Program in java.

Let see the implementation of BST and DST in single program


package inv.learning.searching;

import java.util.Iterator;
import java.util.LinkedList;

public class BFT {

public static void main(String[] args) {

Graph g = new Graph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(1, 4);
System.out.println("Breadth First Search --");
g.BST(0);

System.out.println("Depth first search --");
g.DST(0);

}
}
class Graph{

int V;
LinkedList adj[];

Graph(int v){
V=v;
adj = new LinkedList[v];
for(int i=0;i<v;i++)
{
adj[i]= new LinkedList<>();
}
}
public void addEdge(int v,int w)
{
adj[v].add(w);
}

public void BST(int s)
{
boolean[] visited = new boolean[V];
visited[s]=true;
LinkedList<Integer> queue= new LinkedList<>();
queue.add(s);
while(queue.size()!=0)
{
int n = queue.poll();
System.out.println(n+" ");
Iterator<Integer> itr = adj[n].listIterator();
while(itr.hasNext())
{
int i = itr.next();
if(!visited[i]){
visited[i]=true;
queue.add(i);
}

}
}

}
public void DST(int s){
boolean[]  visited = new boolean[V];

DSTUtil(s, visited);
}

public void DSTUtil(int s, boolean[] visited){
visited[s]=true;
System.out.println(s+" ");
Iterator itr = adj[s].listIterator();
while(itr.hasNext())
{
int i = (int) itr.next();
if(!visited[i])
{
DSTUtil(i, visited);

}
}


}


}

Output-

Breadth First Search --

0 

1 
2 
3 
4 
Depth first search --
0 
1 
4 
2 
3 


Thanks for reading
-Noeik

JVM - Classloading in java

Hello Everyone , Hope you all are doing good , Today we will learn about class loading in java , class loading is very basic topic which most of the programmer dont know, so lets see what and type of classloaders.

--jvm Class Loading---
Three activities while class loading
-loading
-linking
-initialization


Loading--- The class loader reads the .class files and generate the correposnidn binary data.

Let see this with example

import java.lang.reflect.Method;

public class ClassLoading {

public static void main(String[] args) {
Student s1= new Student();
Class c1= s1.getClass();

System.out.println(s1.getClass().getName());
Method[] m = s1.getClass().getMethods();
for(Method m1:m)
{
System.out.println(m1.getName());
}
Student s2 = new Student();
Class c2= s2.getClass();
System.out.println(c1==c2);
}


}


class Student {

String name;
int roll_no;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}

}

Output----
inv.learning.jvm.Student
getRoll_no
setRoll_no
getName
setName
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll
true


NOTE: If we see the line System.out.println(c1==c2) it will give true that means Class c1 and Class c2 always point to same Class Object.
For every loaded .class file, only one object of Class is created.

--------------------------------------------------------
Linking-- Performs verification, preparation, and (optionally) resolution.
Verification : Its ensure the correctness of .class file if not generated by valid compile it will give the runtime exception.
Preparation : JVM allocates memory for class variables and initializing the memory to default values.
Resolution : It is the process of replacing symbolic references from the type with direct references. It is done by searching into method area to locate the referenced entity.

----------------------

Initialization:- In this phase all the static variable and static blocked get the assigned values in the code , it executed from top to bottom and from parent to child.
basically there are 3 type of class loader.
1) Bootstrap class loader- These class loader is essential used to load the trusted classes. Like all the native java api classes which are defined in JAVA_HOME/jre/lib.
2)Extension class loader- child of bootstrap class loader , load all the class of JAVA_HOME/jre/lib/ext .
3) Application class loader - child of extension class loader , used to load the application .class files.

package inv.learning.jvm;

public class ClassLoadingDemo {

public static void main(String[] args) {

// String class is loaded by bootstrap loader, and
        // bootstrap loader is not Java object, hence null
System.out.println(String.class.getClassLoader());

System.out.println(ClassLoadingDemo.class.getClassLoader());
}
}

Thanks for reading
-Noeik

Monday, February 6, 2017

Polymorphism and its type-Java

Hello guys , today we will read about one important characteristice of oops i.e Polymorphism

--polymorphism---

One thing in many form
or
The ability to appear in more than one form

In Java there are 2 type of polymorphism
-compiler time polymoriphism (static binding) -achieved by method overloading

-runtime polymorphism(dynamic binding) -achieved by method overriding

---Overloading---------------
there are 2 type of overloading in java
-method overloading
-constructor overloading
-operator overloading

-------------------------------Method Overloading----------------------------------
If the class contains more than one method with same name and different no. of arguments(return type is not consider in overloadding) or same no. of argument with different data types.
Ex -
class c{
void m1(int a)
void m1(int a , int b)
void m2(char c)
void m2(String str)

}
Method signature - method name and paramters is metehod signature
Real time example-
for Adhar Card we have few options to get the duplicate adhar card
we can provide- dob and name
pan no
name and father name
so here we will use method overloading as we dont know what the user is going to give to fetch its information.

--------------------------------Constructor Overloading--------------
Same constructor name with different no. of arguments or same constructor with same no. of arguments with different data type.

Ex-
class Test
{
Test(int i)
{
syso("one arg constructor with int");
}
Test(int i, int k)
{
syso("2 arg constructor with int");
}
Test(char cs)
{
syso("one arg constructor with char");

}
main()
{
Test t=new Test(1);
Test t1 = new Test(1,2);
Test t3 =new Test('r');

}
}
------------------operator overloading--------------
one operator with more than one behaviour
no java is not supported operator overloading

Only one operator + is defined in java implisitly

Root class of all class is object class
Default package in java is java.lang package


-----------------------------Method Overriding-----------------------------------
To Achieve the overriding we required 2 java classes with inheritance concept

Overriden class is the parent class whose method is going to override
overriding class is the child class whose method will override the parent method
There are some rules of Method Overriding
1) Overridden method signature and child class method signature must be same
2) Return type of both the method must be same at primitive level
3)co varint return type in which the parent class has parent return type and class method is having the sub type of parent return type
4) if a method is declared as final overriding is not possible
-final class methods are final(bcz if it is not a final we will be able to override) but variable is not final
5) static method can't be override
6)child class is not able to hold the parent reference object
ex - Child child = new Parent() // invalid


Hope these points will help you in your preparation .

Thanks for reading
-Noeik



Thursday, February 2, 2017

Basic and tricky java Interview Questions

Hi guys , Hope you all are doing good , Today I am going to share few tricky questions which i felt everyone who is preparing for java interview should know. So lets see

Q1) Difference between new operator and newInstance() method ?/
-    new is used when we know the type of class instance know at design time.
     if you dont know then we use newInstance method
    ex-
     Student std = new Student();
      Object o = Class.forName(arg[0]).newInstance();


Q2) classNotFoundException vs NoClassDefFoundException
       when we write like this
      Test test= new Test();
      and the Test.class file is not found then at runtime we will get NoClassDefException found.                (unchecked exception)
         Object o = Class.forName(args[0]).newInstance();
        will get the ClassNotFoundException (checked exception)



Q3) Diff b/w checked and unchecked exception
exception which are be checked by compiler  how to handle the expection. for the smooth execution of program.
ex- FileNotFoundException is checked exception , compiler ask to handle the exception while compile.
exception which are not checked by compiler
ArthematicException is unchecked exception.


control flow of try catch
if exception in araised in catch block it is abnormal exception

variable combination of try catch final block
- try catch
-try catch catch(catch should be in child to parent heirarchy)
try final
try catch final


------------------String---------------
Why String is always final in java - due to immutability ,security (thread safe) etc
Why we use character array over string to store password ?
-as string is immutable and it is persist till the garbage collector called . As data is stored for long time because string pool used the string data
- if we use JPasswordField then it will also return array[] for getPassword() and depricated getText() field

--------------String Pool-----------------
Why we use string pool ?
String pool is used to store the references of the strings
Ex-
String s=“prasad”;
String s1=“prasad”;
System.out.println(s==s1)  // output  true;

The class is loaded when JVM is invoked.
JVM will look for all the string literals in the program
First, it finds the variable s which refers to the  literal “prasad” and it will be created in the memory
A reference for the literal “prasad” will be placed in the string constant pool memory.
Then it finds another variable s2 which is referring to the same string literal “prasad“.
Now that JVM has already found a string literal “prasad“, both the variables s and s2 wil refer to the same object i.e. “prasad“.
----intern() --------------
intern method check whether the string is present in spring pool if yes then return the reference of the string otherwise create new string object
Ex-
String s ="prasad";
String s1="prasad".intern();
System.out.println(s==s1)  // output true
System.out.println(s.equals(s1));   // output true

String s ="prasad";
String s1="prasad1".intern();
System.out.println(s==s1)  // output false
System.out.println(s.equals(s1));   // output false

---------------------------

Difference btw encapculation & abstraction(how to achieve abstraction using encp)
- by decreasing the scope of behaviour(methods)
encapsulation - wrapping of data and associated func into a single unit is encp -(class)
Ex-
if we have one function which will call the other function so we can scope down the other function to achieve abstraction

Class A{

public void m1()
{
m4internal();
}
public void m2()
{
}
}
Class B{

protected void m4internal()

}

Hope these will be helpful for you , if you have any problem , do let me know

Thanks for Reading
-Noeik

Thursday, January 12, 2017

Inheritance - Indepth- Important Topic of Interview of Java

Hi Guys, Yesterday I posted about Inheritance , what how and type of inheritance . today i am going to post articles about the Indepth knowledge of inheritance, So lets starts

HOW TO PREVENT THE CLASS FROM INHERITANCE
to prevent the class from inherit , we should use final modifier
Ex-
Class A{
}
Class B extends A{
}
OUTPUT - inheritance possible
final Class A{
}
Class B extends A
{
}
Output -inheritnace not possible as class is final (cannot inherit from final )

this keyword - to indicate the current object
super keyword is used to indicate the parent object of the current Object

USE OF SUPER KEYWORD IN INHERITANCE

Class Parent{

Parent()
{
syso("this is parent 0-arg constrctr");
}
}
Class Child extends Parent
{
Child()
{
this(10)    // to call child 1 args constructor
syso("child 0-arg constructor")
}
Child(int agr)
{
super()  // to call parent 0 args constructor
syso ("child 1-arg constructor");
}

psvm(string[] args)
{
new Child();
}
}
NOTE - SUPER & THIS CALL MUST BE FIRST STATEMENT IN CONSTRUCTOR
NOTE 2 - SUPER & THIS BOTH CANT BE POSSIBLE TO CALL IN SAME CONSTRUCTOR
NOTE 3- CHILD CLASS CONSTRUCTOR WILL ALWAYS CALL ANOTHER CONSTRUCTOR EITHER EXPLICIT OR IMPLICIT IF WE DON'T SPECIFY THE CONSTRUCTOR THEN SUPER() WILL BE CALLED

* compiler generated code always called zero argument constructor
* if we created one arg constructor then we will have to create zero arg constructor else it will generate compiler error

Instance block execute first then constructor execute (in inheritance case - parent class instance block then child class instance block)

Hope you guys understand the points i am trying to make, Let me know if you have any problem , Will be happy to help

-Thanks for Reading
-Noeik

Tuesday, January 10, 2017

Inheritance- Basics - Important Topic for Interview

Guys , Hope you are doing well , Today i am again back with some good article , today i will try to write something which i think is one of the favorite topic of all time for an interviewer.

So Inheritance , Most of you knows what is inheritance but the actual in depth knowledge of inheritance is very much required while you are preparing for interview.
In my earlier post I have talked about Tower of Hanoi problem 
You can also see other Sorting program
Bubble Sort 
Selection Sort
Insertion Sort 
  • What is Inheritance  ?
    • In general - acquiring the properties and character tics of parent by child. 

 
Class A   // parent class
{ void m1();
void m2();
}
Class B extends A   // child class(class B has method m1 & m2 available)
{
void m3();
void m4();
}

ADVANTAGES OF INHERITANCE

-reduce the redundance 
- reduce the length of code;

NOTE - One class only extends one class (not more than one class)

B b = new B();  // we can access 4 method using b object;
A a = new A();   // only access 2 methods;

Interview Question - recommended to create the object of parent or child class ?? 
ans - child - bcz it is possible to access parent method also;

NOTE - root class is the class which is not extending any class.
-- root class of all java classes -> Object class (package java.lang )

TYPE OF INHERITANCE-

  • -single level inheritance
  • -multiple inheritance
  • -multilevel inheritance
  • -hirarical inheritance
  • -hybrid inheritance
---SINGLE LEVEL INHERITANCE---
when a class is extending only one parent class and the class is not extended by any other class
Ex- 
Class A {
void m1()
}
Class B extends A 
{

void m2()
}

---multilevel inheritance
Ex- 
Class A {
void m1()
}
Class B extends A{
void m2()
}
Class C extends B {
void m3()
}

--heirarical inheritance

Ex 
Class A
{
}
Class B extends A
{
}
Class C extends A
{
}
Class D extends A
{
}

--multiple inheritance

Ex
Class A
{
void money ()

}
Class B 
{
void money ()
}
Class C extends B, A
{
}
 NOTE - now when c is trying to access , then obviously ambiguity occured for c object which method to call(SO IT IS NOT SUPPORTED BY JAVA)(diamond problem )
 --HYBRID INHERITANCE = MULTIPLE + HEIRARICAL  (java is not supporting multiple so java is not supporting hybrid)


In Next Article we will have Inheritance in depth article , If you have any problem in this post , do let me know , I will try to solve your problem , Do Comment in comment section .

Thanks for Reading

-Noeik

     


Wednesday, December 14, 2016

String Class in Java


String is one of the most used class in java programing language , let see what makes it very useful class in java as well as its properties.



So lets Start with

1) What is String ?

So String is a Class in Java , which is basically the array of characters , In Java String is Class
,not a primitive datatype as in C  language.

Package Name - java.lang.String

2) How can you say that String is immutable in java ?

So we should first understand what is immutable means , So immutable means when any object is not permit itself to be modified or changed. so how string is immutable in java , lets see by example

class StringManupulation

{

 public static void main (String[] args) throws java.lang.Exception

 {

  // your code goes here

  String str1= new String("Program");

  str1.concat("In Java");

          System.out.println(str1);

 }

}

Output :- Program

Logic - As String is immutable it is not allowing the object to be modified as the object initial refer to Program and after concat it with another string , It is not allowing itself to modified


class StringManupulation

{

 public static void main (String[] args) throws java.lang.Exception

 {

  // your code goes here

  String str1= new String("Program");

  str1+=str1.concat("In Java");

          System.out.println(str1);

 }

}

Output : Program In Java

Logic:- As we are changing the reference of the Str1 to Str1+ "In java" Object so the String str1 is now pointing to different object hows valus is "Program In Java".


Difference btw string and string buffer ?

  • String is immutable and StringBuffer is mutable
    • immutable - means the string will not be modify after created
Why String is immutable?
String object are cached in string pool and these strings are shared so changing values has risk.
security reasons-
  • if string is mutable then user could have changed the path after logging.
  • would have changed the db url
  • Mutable string cause problem in reflection also.
Immutability with examples
Non Changing behaviour is called immutability
Example-
String s = new String("programinjava");
s.concat(".com");
System.out.println(s);

Output : programinjava

Second Example:- 

String s1 = new String("programinjava");
String s2= new String ("programinjava");
System.out.println(s1==s2) 
System.out.println(s.equals(s2)) 
Output:

false
true

In String class .equals Method meant for content check
Explanation:-
String s = new String("programinjava");

  •  2 object created , One is in Heap area and other one is in String constant pool ,s is pointing to Heap Object

String s= "programinjava" ;

  • 1 object created in string constant pool
  • Garbage collector is not allowed to access String pool area.

Memory area in java

There are 5 memory area are there in java - 

  1. Heap(garbage collected is applicable only for heap)
  2. Method Area (SCP is in Method area)
  3. Stack
  4. PC Register
  5. Native Method stacks

Whenever we use new operator with string , it will compulsory create object in heap and put it in  Method Area

Example-
How many object will create ?
String s1 = new String("programinjava"); // 1 h 1 scp
String s2 = new String("programinjava");// 1 h , pre scp
String s3="programinjava";// previous scp
String s4 ="programinjava";// previous scp
There are total 3 object;// 2 in heap and 1 in scp

Runtime opertion on string will create object in heap

Examples-
String s = new String("programinjava");
s =s.concat(".com");
Explanation:
Here ,
"programinjava" will be in heap and scp
s.concat will create one string constant in scp ".com"
and create object "programinjava.com" in heap area

NOTE1-For every string constant , one object will be placed in scp area.
NOTE2 - At Runtime if an object is required to placed only in heap area but not in scp area.


Mutable with examples


StringBuffer sb = new StringBuffer("programinjava");
sb.append(".com");
System.out.println(sb);
Output: programinjava.com

StringBuffer sb1 = new StringBuffer("durga");
StringBuffer sb2 = new StringBuffer("durga");
System.out.println(sb1==sb2); //false
System.out.println(sb1.equals(sb2) ); //false

In StringBuffer Class .equals method meant for reference check

If you have any problem in understanding this , Please let me know in Comment section.

Thanks For Reading 
-Noeik