Tuesday, October 3, 2017

Run-time Stack mechanism in Java

Run-time Stack mechanism in Java

Ans:

For every thread that you create,JVM (Java virtual machine) creates a run-time stack.

1)Each and every call performed in a thread is stored in the stack.

2)Each entry in the run-time stack is known as activation record or stack frame.

3)After completing every method call by the thread then all the corresponding entry of the stack will be removed.

4)After completing all the methods, the stack will be empty and that run-time stack will be destroyed by the JVM before terminating the thread.

Normally:

Construction of run-time Stack : 

1. Firstly, the main thread will call main() method and the corresponding entry will be in the stack.

2. After that main() method is calling fun() method, which will store in the stack.

3. In the fun() method, moreFun() method is called. Therefore at last moreFun() will be stored in stack.

4. Finally, moreFun() is not calling any method and it will print Hello Guys!

Example:

class Test {
public static void main(String[] args)
{
fun();
}
public static void fun()
{
moreFun();
}
public static void moreFun()
{
System.out.println("Hello Guys!");
}
}

Output: Hello Guys!



Destruction of run-time stack : 

After printing Hello Guys!, its corresponding entry will be removed from the stack and it will go to fun() method and there is nothing for execution that’s why the entry of fun() method is removed from the stack and so on.When the stack is empty then the run-time stack is destroyed by the JVM.



Abnormally

Construction of run-time Stack :

1. The example below have ArithmeticException at method moreFun() location, the JVM will check any exception handling code is there. If not, then method moreFun() will be responsible to create exception object because of exception are raised on method moreFun() and corresponding entry from the stack will be removed and the control goes to method fun().

2. JVM again go to the caller method to check if it is having any exception handling code are not. If not JVM terminates the method abnormally and deleted the corresponding entry from the stack.

3. The above process continues until main thread. If the main thread(main method) doesn’t have any exception handling code the JVM also terminates the main method abnormally and default exception handler is responsible to print the exception message to the output screen which is the part of JVM.

Sample Code:

public class Test {
public static void main(String[] args)
{
fun();
}
public static void fun()
{
moreFun();
System.out.println("Method fun");
}
public static void moreFun()
{
System.out.println(10 / 0);
System.out.println("Method moreFun");
}
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.moreFun(Test.java:14)
at Test.fun(Test.java:9)
at Test.main(Test.java:5)





Destruction of run-time stack:







Most frequent word in an array of strings? OR Find winner of an election where votes are represented as candidate names?

Question:

Most frequent word in an array of strings?

                                                    OR

Find winner of an election where votes are represented as candidate names?

Solution:

Given an array of names of candidates in an election. A candidate name in array represents a vote casted to the candidate. Print the name of candidates received Max vote. If there is tie, print lexicographically smaller name.

               OR
Given an array of words find the most occurring word in it.

Input : arr[] = {"Abhinaw", "for", "Abhinaw", "Abhinaw",
                "portal", "to", "learn", "can",
                "be", "computer", "science",
                 "zoom", "yup", "fire", "in",
                 "be", "data"}

Output : Abhinaw

"Abhinaw" is the most frequent word as it.
occurs 3 times

So i can think of like this:

Run two loops and count occurrences of every word.

Time complexity of this solution is O(n * n * MAX_WORD_LEN).

Bu i have an another efficient solution also which is below:

Trie data structure: The idea is simple first we will insert in trie. In trie, we keep counts of words ending at a node. We do preorder traversal and compare count present at each node and find the maximum occurring word.

Time Complexity : O(n * MAX_WORD_LEN)

I have  Hashing solution also and which is more efficient solution than above.Have a look into the code.

Sample Code:

import java.util.HashMap;
import java.util.Map;

/**
 *
 */

/**
 * @author Abhinaw.Tripathi
 *
 */
public class MostFrequentWordOrElectricVotingApp
{
public static void main(String[] args)
{
String[] votes = { "Abhinaw", "Gaurav", "Abhishek",
"Garima", "babli", "Logesh",
"Lalitha", "Pawan", "Abhinaw",
"Abhinaw", "Garima", "Abhinaw",
"Abhinaw" };

        findWinner(votes);
}

public static void findWinner(String votes[])
       {
        Map<String,Integer> map =new HashMap<String, Integer>();
        for (String str : votes)
        {
            if (map.keySet().contains(str))
                map.put(str, map.get(str) + 1);
            else
                map.put(str, 1);
        }
        int maxValueInMap = 0;
        String winner = "";
 
        for ( Map.Entry<String,Integer> entry : map.entrySet())
        {
            String key  = entry.getKey();
            Integer val = entry.getValue();
            if (val > maxValueInMap)
            {
                maxValueInMap = val;
                winner = key;
            }

            // If there is a tie, pick the
            else if (val == maxValueInMap && winner.compareTo(key) > 0)
                winner = key;
        }
        System.out.println("Winning Candidate is :" +winner);
    }

}

 Output: 

 Winning Candidate is :Abhinaw






 

Wednesday, September 27, 2017

Design Pattern- Comparison between MVC,MVP and MVVM in Android Application Development?

Comparison between MVC,MVP and MVVM in Android Application Development?

I often get questions that which one is better MVC,MVP and MVVM when you are developing Android application.So i have decided to give the overview on all of them.

The best practices approach for developing Android applications into logical components has evolved over the last few years. The community has largely moved away from the monolithic Model View Controller (MVC) pattern in favor of more modular, testable patterns.

Model View Presenter (MVP) & Model View ViewModel (MVVM) are two of the the most widely adopted alternatives, but developers are often divided  as to which one better.So lets take a look into it.

MVC

The model, view, controller approach separates your application at a macro level into 3 sets of responsibilities.

Model

The model is the Data + State + Business logic of any application. It’s the brains of any application so to speak. It is not tied to the view or controller, and because of this, it is reusable in many contexts.

View

The view is the Representation of the Model. The view has a responsibility to render the User Interface (UI) and communicate to the controller when the user interacts with the application. In MVC architecture, Views are generally pretty "dumb" in that they have no knowledge of the underlying model and no understanding of state or what to do when a user interacts by clicking a button, typing a value, etc. The idea is that the less they know the more loosely coupled they are to the model and therefore the more flexible they are to change.

Controller

The controller is basically a Glue that ties the app together. It’s the master controller for what happens in the application. When the View tells the controller that a user clicked a button, the controller decides how to interact with the model accordingly. Based on data changing in the model, the controller may decide to update the state of the view as appropriate. In the case of an Android application, the controller is almost always represented by an Activity or Fragment.


             ----> Notify                                        --------->Interact with
View<------------------------>Controller------------------------------------>Model
          Setup View  <-----


Evaluation

MVC does a great job of separating the model and view. Certainly the model can be easily tested because it’s not tied to anything and the view has nothing much to test at a unit testing level.

The Controller has a few problems however.
Controller Concerns

Testability - The controller is tied so tightly to the Android APIs that it is difficult to unit test.

Modularity & Flexibility - The controllers are tightly coupled to the views. It might as well be an extension of the view. If we change the view, we have to go back and change the controller.

Maintenance - Over time, particularly in applications with anemic models, more and more code starts getting transferred into the controllers, making them bloated and brittle.

How can we address this? MVP to the rescue!

MVP

MVP breaks the controller up so that the natural view/activity coupling can occur without tying it to the rest of the “controller” responsibilities. More on this below, but let’s start again with a common definition of responsibilities as compared to MVC.

Model

Same as MVC / No change

View

The only change here is that the Activity/Fragment is now considered part of the view. We stop fighting the natural tendency for them to go hand in hand. Good practice is to have the Activity implement a view interface so that the presenter has an interface to code to. This eliminates coupling it to any specific view and allows simple unit testing with a mock implementation of the view.

Presenter

This is essentially the controller from MVC except that it is not at all tied to the View, just an interface. This addresses the testability concerns as well as the modularity/flexibility concerns we had with MVC. In fact, MVP purists would argue that the presenter should never have any references to any Android APIs or code.

                         ----> Notify                         --------->Interact with
View<----------------------------->Presenter------------------------------------>Model
         Ask view to Setup Itself

Evaluation

This is much cleaner. We can easily unit test the presenter logic because it’s not tied to any Android specific views and APIs and that also allows us to work with any other view as long as the view implements the interface.

Presenter Concerns

Maintenance - Presenters, just like Controllers, are prone to collecting additional business logic, sprinkled in, over time. At some point, developers often find themselves with large unwieldy presenters that are difficult to break apart.

Of course, the careful developer can help to prevent this, by diligently guarding against this temptation as the application changes over time. However, MVVM can help address this by doing less to start.

MVVM

MVVM with Data Binding on Android has the benefits of easier testing and modularity, while also reducing the amount of glue code that we have to write to connect the view + model.

Let’s examine the parts of MVVM.

Model

Same as MVC / No change

View

The view binds to observable variables and actions exposed by the viewModel in a flexible way. More on that in minute.

ViewModel

The ViewModel is responsible for wrapping the model and preparing observable data needed by the view. It also provides hooks for the view to pass events to the model. The ViewModel is not tied to the view however.


               ---->Invoke Action                                          --------->Interact with
View----------------------------->ViewModel(Interface)------------------------------------>Model
              ----->Bind To Data


page for some more great examples of MVVM & Data Binding.

Evaluation

Unit testing is even easier now, because you really have no dependency on the view. When testing, you only need to verify that the observable variables are set appropriately when the model changes. There is no need to mock out the view for testing as there was with the MVP pattern.

MVVM Concerns

Maintenance - Since views can bind to both variables and expressions, extraneous presentation logic can creep in over time, effectively adding code to our XML. To avoid this, always get values directly from the ViewModel rather than attempt to compute or derive them in the views binding expression. This way the computation can be unit tested appropriately.

Conclusions

Both MVP and MVVM do a better job than MVC in breaking down your app into modular, single purpose components, but they also add more complexity to your app. For a very simple application with only one or two screens, MVC may work just fine. MVVM with data binding is attractive as it follows a more reactive programming model and produces less code.

So which pattern is best for you? If you’re choosing between MVP and MVVM, a lot of the decision comes down to personal preference, but seeing them in action will help you understand the benefits and tradeoffs.



Tuesday, September 26, 2017

Reverse a string in Java in 5 Different Ways?

Reverse a string in Java in 5 Different Ways?.

Ans: its very easy though and very popular question in interview.So thought of giving my inputs
on it.

Examples:

Input :  abhinaw
Output : wanihba

Input: Abhinaw Tripathi
Output: ihtapirT wanihbA

Before,dig in would like to tell you some interesting facts about String and StringBuffer classes:

1. Objects of String are immutable.

2. String class in Java does not have reverse() method, however StringBuilder class has built in reverse() method.

3. StringBuilder class do not have toCharArray() method, while String class does have toCharArray() method.

So the first ways is using:

1)Converting String into Bytes:

getBytes() method is used to convert the input string into bytes[].

Method:

 1. Create a temporary byte[]  of length equal
   to the length of the input string.
 
2. Store the bytes (which we get by using
   getBytes() method) in reverse order into
   the temporary byte[] .
 
3. Create a new String abject using byte[] to
   store result.
 
   Sample Code:
 
 
import java.lang.*;
import java.io.*;
import java.util.*;

class ReverseStringTest
{
public static void main(String[] args)
{
String input = "abhinaw";

byte [] strAsByteArray = input.getBytes();

byte [] result =
new byte [strAsByteArray.length];

for (int i = 0; i<strAsByteArray.length; i++)
result[i] =
strAsByteArray[strAsByteArray.length-i-1];

System.out.println(new String(result));
}
}

Output:

wanihba

2)Using built in reverse() method of the StringBuilder class: 

String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder. After that, print out the characters of the reversed string by scanning from the first till the last index.

Sample Code:

import java.lang.*;
import java.io.*;
import java.util.*;

class ReverseStringTest
{
public static void main(String[] args)
{
String input = "abhinaw";

StringBuilder input1 = new StringBuilder();

input1.append(input);

input1 = input1.reverse();

// print reversed String
for (int i=0; i<input1.length(); i++)
System.out.print(input1.charAt(i));
}
}

Output:
wanihba

3) Converting String to character array: 

The user input the string to be reversed.

Method:
1. First, convert String to character array
   by using the built in Java String class
   method toCharArray().
2. Then, scan the string from end  to start,
   and print the character one by one.
 
 SampleCode:


import java.lang.*;
import java.io.*;
import java.util.*;

class ReverseString
{
public static void main(String[] args)
{
String input = "Abhinaw";
char[] try1 = input.toCharArray();

for (int i = try1.length-1; i>=0; i--)
System.out.print(try1[i]);
}
}

Output: wanihbA

4) Convert the input string into character array by using the toCharArray(): 

Convert the input string into character array by using the toCharArray() – built in method of the String Class. Then, scan the character array from both sides i.e from the start index (left) as well as from last index(right) simultaneously.

1. Set the left index equal to 0 and right
   index equal to the length of the string -1.
2. Swap the characters of the start index
   scanning with the last index scanning
   one by one. After that, increase the left
   index by 1 (left++) and decrease the right
   by 1 i.e., (right--) to move on to the next
   characters in the character array .
3. Continue till left is less than or equal to
   the right.
   
   SampleCode:
 
import java.lang.*;
import java.io.*;
import java.util.*;

class ReverseStringTest
{
public static void main(String[] args)
{
String input = "Abhinaw Tripathi";
char[] temparray = input.toCharArray();
int left, right=0;
right = temparray.length-1;

for (left=0; left < right ; left++ ,right--)
{
char temp = temparray[left];
temparray[left] = temparray[right];
temparray[right]=temp;
}

for (char c : temparray)
System.out.print(c);
System.out.println();
}
}

Output:

ihtapirT wanihbA

5)Using ArrayList object:

 Convert the input string into the character array by using toCharArray() built in method. Then, add the characters of the array into the ArrayList object. Java also has built in reverse() method for the Collections class. Since Collections class reverse() method takes a list object , to reverse the list , we will pass the LinkedList object which is a type of list of characters.

1. We copy String contents to an object
   of ArrayList.
1. We create a ListIterator object by using
   the listIterator() method on the LinkedList
   object.
2. ListIterator object is used to iterate over
   the list.
3. ListIterator object helps us to iterate
   over the reversed list and print it one
   by one to the output screen.
   
SampleCode:

import java.lang.*;
import java.io.*;
import java.util.*;

class ReverseStringTesting
{
public static void main(String[] args)
{
String input = "Abhinaw Tripathi";
char[] hello = input.toCharArray();
List<Character> trial1 = new ArrayList<>();

for (char c: hello)
trial1.add(c);

Collections.reverse(trial1);
ListIterator li = trial1.listIterator();
while (li.hasNext())
System.out.print(li.next());
}
}

Output: ihtapirT wanihbA

Swap two Strings without using third user defined variable in Java

Ans:

Given two string variables a and b, swap these variables without using temporary or third variable in Java. Use of library methods is allowed.

Examples:

Input: a = "Hello"
       b = "World"

Output:

Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello

Solution Algorithm:

1) Append second string to first string and
   store in first string:
   a = a + b

2) call the method substring(int beginindex, int endindex)
   by passing beginindex as 0 and endindex as,
      a.length() - b.length():
   b = substring(0,a.length()-b.length());

3) call the method substring(int beginindex) by passing
   b.length() as argument to store the value of initial
   b string in a
   a = substring(b.length());
 
   
 Sample Code:

import java.util.*;

class SwapTest
{
public static void main(String args[])
{
String a = "Hello";
String b = "World";

System.out.println("Strings before swap: a = " + a + " and b = "+b);
a = a + b;
b = a.substring(0,a.length()-b.length());
a = a.substring(b.length());
System.out.println("Strings after swap: a = " + a + " and b = " + b);
}
}

Output:

Strings before swap: a = Hello and b = World
Strings after swap: a = World and b = Hello

Java.util.StringJoiner in Java 8 Example

Java.util.StringJoiner in Java 8 Example

Ans:I hope everybody knows about it.i am just giving my inputs on it.So

StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
Though, this can also be with the help of StringBuilder class to append delimiter after each string, but StringJoiner provides easy way to do that without much code to write.

Constructors of StringJoiner :

1)StringJoiner(CharSequence delimiter) : 

Small description of it.

Syntax :

public StringJoiner(CharSequence delimiter)
Parameters :
delimiter - the sequence of characters to be used between
each element added to the StringJoiner value

Throws:
NullPointerException - if delimiter is null

2)StringJoiner(CharSequence delimiter,CharSequence prefix,CharSequence suffix) : 

Syntax :

public StringJoiner(CharSequence delimiter,
       CharSequence prefix, CharSequence suffix)
 
Parameters :
delimiter - the sequence of characters to be used between
each element added to the StringJoiner value
prefix - the sequence of characters to be used at the beginning
suffix - the sequence of characters to be used at the end

Throws:
NullPointerException - if prefix, delimiter, or suffix is null

Methods : There are 5 methods in StringJoiner class.

1)String toString() : 

Syntax :

public String toString()
Parameters :
NA
Returns :
the string representation of this StringJoiner
Overrides :
toString in class Object

2)StringJoiner add(CharSequence newElement) :

Syntax :
public StringJoiner add(CharSequence newElement)
Parameters :
newElement - The element to add
Returns :
a reference to this StringJoiner

3)StringJoiner merge(StringJoiner other) :

Syntax :
public StringJoiner merge(StringJoiner other)
Parameters :
other - The StringJoiner whose contents should be merged
into this one
Returns :
This StringJoiner
Throws :
NullPointerException - if the other StringJoiner is null

4)int length() : 

Syntax :
public int length()
Parameters :
NA
Returns :
This StringJoiner

5)StringJoiner setEmptyValue(CharSequence emptyValue) :

Syntax :
public StringJoiner setEmptyValue(CharSequence emptyValue)
Parameters :
emptyValue - the characters to return as the value
of an empty StringJoiner
Returns :
this StringJoiner itself so the calls may be chained
Throws:
NullPointerException - when the emptyValue parameter is null

Sample Program for StringJoiner:

import java.util.ArrayList;
import java.util.StringJoiner;

public class SampleProgram
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<>();

al.add("Abhinaw");
al.add("Abhishek");
al.add("Ram");
al.add("VirtualRelaity");

StringJoiner sj1 = new StringJoiner(",");

// setEmptyValue() method
sj1.setEmptyValue("sj1 is empty");
System.out.println(sj1);

// add() method
sj1.add(al.get(0)).add(al.get(1));
System.out.println(sj1);

// length() method
System.out.println("Length of sj1 : " + sj1.length());

StringJoiner sj2 = new StringJoiner(":");
sj2.add(al.get(2)).add(al.get(3));

//merge() method
sj1.merge(sj2);

// toString() method
System.out.println(sj1.toString());

System.out.println("Length of new sj1 : " + sj1.length());

}
}

Output:

sj1 is empty
Abhinaw,Abhishek
Length of sj1 : 16
Abhinaw,Abhishek,Ram:VirtualRelaity
Length of new sj1 : 35


Monday, September 25, 2017

Covariant return types in Java with Example

Covariant return types in Java Example

Its a very trending interview question now so thought of sharing some of my inputs
on it.

So,before going deep into it.i would like to answer this question very generic ways like
before java JDK verion 5.0.It was not possible to override a method by changing the return type.

When we override a parent class method, the name, argument types and return type of the overriding method in child class has to be exactly same as that of parent class method. Overriding method was said to be invariant with respect to return type.Now if you have notice
two keyword such as Covariant and Invariant So what are those two keywords?.

Covariant return types

Java JDK version 5.0 onwards it is possible to have different return type for a overriding method in child class, but child’s return type should be sub-type of parent’s return type. Overriding method becomes variant with respect to return type.

So all this concept is based on one PRINCIPLE which is Liskov substitution principle.
Now what is this PRINCIPLE?
Let me give breife of this principle.

Liskov substitution principle:

Substitutability is a principle in object-oriented programming stating that, in a computer program, if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e. an object of type T may be substituted with any object of a subtype S) without altering any of the desirable properties of T (correctness, task performed, etc.).

 More formally, the Liskov substitution principle (LSP) is a particular definition of a subtyping relation, called (strong) behavioral subtyping, that was initially introduced by Barbara Liskov in a 1987 conference keynote address titled Data abstraction and hierarchy. It is a semantic rather than merely syntactic relation because it intends to guarantee semantic interoperability of types in a hierarchy, object types in particular.

 Subtype Requirement: Let {\displaystyle \phi (x)} \phi (x) be a property provable about objects {\displaystyle x} x of type T. Then {\displaystyle \phi (y)} {\displaystyle \phi (y)} should be true for objects {\displaystyle y} y of type S where S is a subtype of T.

 In Layman term,i would rather say this.have a look.

Liskov Substitution Principle,As per the LSP, functions that use references to base classes must be able to use objects of the derived class without knowing it. In simple words, derived classes must be substitutable for the base class. To illustrate the LSP, let’s take an example of rectangles and squares. One tends to establish the ISA relationship, thus, you can say that a square a rectangle. However, there arises a problem (hence, a violation of the LSP).Lets not
go in fuirther details of it.Just keep the above points in your mind for Covariant return types in Java.

Let me provide a simple Code for better understanding:

class A {}
class B extends A {}

class Base
{
    A fun()
    {
        System.out.println("Base fun()");
        return new A();
    }
}

class Derived extends Base
{
    B fun()
    {
        System.out.println("Derived fun()");
        return new B();
    }
}

public class Main
{
    public static void main(String args[])
    {
       Base base = new Base();
       base.fun();

       Derived derived = new Derived();
       derived.fun();
    }
}

Output:

Base fun()
Derived fun()

Note : If we swap return types of Base and Derived, then above program would not work.

Advantages:

1)It helps to avoid confusing type casts present in the class hierarchy and thus making the code readable, usable and maintainable.

2)We get a liberty to have more specific return types when overriding methods.
3)Help in preventing run-time ClassCastExceptions on returns.








Saturday, September 23, 2017

NullPointer Exception(null) and its facts in JAVA with example

Facts about null in Java with example

So let me tell you some interesting facts about null in Java

Almost all the programming languages are bounded with null. There is hardly a programmer, who is not troubled by null.

In Java, null is associated java.lang.NullPointerException.

it is a class in java.lang package, it is called when we try to perform some operations with or without null and sometimes we don’t even know where it has happened.

Below are some important points about null in java which every Java programmer should know:

1. null is Case sensitive: null is literal in Java and because keywords are case-sensitive in java, we can’t write NULL or 0 as in C language.

public class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // compile-time error : can't find symbol 'NULL'
        Object obj = NULL;
       
        //runs successfully
        Object obj1 = null;
    }
}


Output:

5: error: cannot find symbol
 can't find symbol 'NULL'
                 ^
   variable NULL
 class Test
1 error


2. Reference Variable value: Any reference variable in Java has default value null.

public class Test
{
    private static Object obj;
    public static void main(String args[])
    {
        // it will print null;
        System.out.println("Value of object obj is : " + obj);
    }
}

Output:

Value of object obj is : null


3. Type of null: common misconception, null is not an Object or neither a type. It’s just a special value, which can be assigned to any reference type and you can type cast null to any type

Examples:

    // null can be assigned to String
    String str = null;
   
    // you can assign null to Integer also
    Integer itr = null;
   
    // null can also be assigned to Double
    Double dbl = null;
       
    // null can be type cast to String
    String myStr = (String) null;
   
    // it can also be type casted to Integer
    Integer myItr = (Integer) null;
   
    // yes it's possible, no error
    Double myDbl = (Double) null;

4. Autoboxing and unboxing : During auto-boxing and unboxing operations, compiler simply throws Nullpointer exception error if a null value is assigned to primitive boxed data type.

public class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
            //An integer can be null, so this is fine
            Integer i = null;
           
            //Unboxing null to integer throws NullpointerException
            int a = i;
    }
}

Output:

 Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:6)


5. instanceof operator: The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). At run time, the result of the instanceof operator is true if the value of the Expression is not null.
This is an important property of instanceof operation which makes it useful for type casting checks.

public class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Integer i = null;
        Integer j = 10;
           
        //prints false
        System.out.println(i instanceof Integer);
       
        //Compiles successfully
        System.out.println(j instanceof Integer);
    }
}

Output:

false
true

6. Static vs Non static Methods: We cannot call a non-static method on a reference variable with null value, it will throw NullPointerException, but we can call static method with reference variables with null values. Since static methods are bonded using static binding, they won’t throw Null pointer Exception.

public class Test
{            
    public static void main(String args[])
    {
        Test obj= null;
        obj.staticMethod();
        obj.nonStaticMethod();                            
    }
   
    private static void staticMethod()
    {
        //Can be called by null reference
        System.out.println("static method, can be called by null reference");
       
    }
       
    private void nonStaticMethod()
    {
        //Can not be called by null reference
        System.out.print(" Non-static method- ");
        System.out.println("cannot be called by null reference");
       
    }

}

Output:

static method, can be called by null referenceException in thread "main"
java.lang.NullPointerException
    at Test.main(Test.java:5)


7. == and != The comparision and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java.

public class Test
{            
    public static void main(String args[])
    {
   
    //return true;
    System.out.println(null==null);
   
    //return false;
    System.out.println(null!=null);
       
    }
}

Output:

true
false