Core Java



Java interview questions


What’s the difference between an Abstract Class and Interface in Java?
An abstract class and interface is that an interface can only possess declaration of public static methods with no concrete implementation while an abstract class can have members with any access specifiers (public, private etc.) with or without concrete implementation.

Another key difference in the use of abstract classes and interfaces is that a class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesn’t require implementation of all the methods of its super class.
A class can implement multiple interfaces but it can extend only one abstract class.


What is the difference between == operator and equals() method
== is shallow comparison which actually compare two object references to see if they point to the same object. While equals (), method is used for deep comparison that compares the actual string values.
The default equals () method on java.lang.Object compares memory addresses, which means that all objects are different from each other (only two references to the same object will return true).


Strings are interned in Java?
String creation is designed with the Flyweight design pattern. Flyweight is all about re-usability without having to create too many objects in memory. String class maintain string literal pool. When the intern ( ) method is invoked it uses equals (..) method to check if the String already exist in the pool. If it does then the String from the pool is returned instead of creating a new object. If it’s not in the string pool, a new String object is created in the pool and a reference to this object is returned. For any two given strings s1 & s2, s1.intern ( ) == s2.intern ( ) only if s1.equals (s2) is true.
String s = “abc” by default use intern behavior.
But using new keyword will create new instances like
String str1 = new String (“ABC”)
String str2 = new String (“ABC”)
Here str1 and str2 are two different instances.


What is use of serialVersionUID?
serialVersionUID is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object which is compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long
<any access modifier>  static final long serialVersionUID = 12L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values


What is the difference between final, finally and finalize() in Java?
When we declare a final keyword use to make a class or variable unmodifiable

Finally block is used to execute default code in case of exception handling, finally block will always execute except System.exit()
If an exception is thrown in finally block and not handled then remaining code in finally block may not be executed.

Finalize method is used before the object is garbage collected so we can put some logic in finalize () method before GC take place.


What is difference between HashMap and HashTable?
HasTable is legacy collection which is synchronized while HasMap is not synchronized.
HasTable doesn’t allow null key or null value while HashMap allow one null key and multiple null values.


What is a thread local variable in Java?
Thread-local variables are variables confined to a thread, it’s like thread's own copy which is not shared between multiple threads. Java provides a ThreadLocal class to support thread-local variables.


What is difference between fail-fast and fail-safe?
Fail fast is nothing but immediately report any failure. whenever a problem occurs fail fast system fails.
in java Fail fast iterator while iterating through collection of objects sometimes concurrent modification exception will come there are two reasons for this.
If one thread is iterating a collection and another thread trying to modify the collection.
And after remove() method call if we try to modify collection object


What is difference between Iterator, ListIterator and Enumeration?
Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException
Enumeration -hasMoreElement(), nextElement()
Iterator - hasNext(), next(), remove()

Iterator is used for traversing List and Set both only in forward direction
We can use ListIterator to traverse List only, we cannot traverse Set using ListIterator in both direction forward and backword.
We cannot obtain indexes while using Iterator but we can obtain indexes at any point of time while traversing a list using ListIterator.
We cannot add element to collection while traversing it using Iterator, it throws ConcurrentModificationException but we can add element at any point of time while using ListIterator.


 How HashSet internally works?
Whenever we insert an element into HashSet using add() method, it actually creates an entry in the internally backing HashMap object with element we have specified as its key and constant as its value.


What is difference between Executor.submit() and Executer.execute() method ?
execute(Runnable) does not return anything.However, submit(Callable<T>) returns a Future object which allows a way to programatically cancel the running thread later as well as get the T that is returned when the Callable completes.


Explain Differences between Collection API and Stream API?
S.NO.
COLLECTION API
STREAM API
1
It’s available since Java 1.2
It is introduced in Java SE8
2
It is used to store Data(A set of Objects).
It is used to compute data(Computation on a set of Objects).
3
We can use both Spliterator and Iterator to iterate elements.
We can use both Spliterator and Iterator to iterate elements.
4
It is used to store limited number of Elements.
It is used to store either Limited or Infinite Number of Elements.
5
Typically, it uses Internal Iteration concept to iterate Elements.
It uses External Iteration to iterate Elements.
6
Collection Object is constructed Eagerly.
Stream Object is constructed Lazily.
7
We add elements to Collection object only after it is computed completely.
We can add elements to Stream Object without any prior computation. That means Stream objects are computed on-demand.
8
We can iterate and consume elements from a Collection Object at any number of times.
We can iterate and consume elements from a Stream Object only once.



What is Spliterator in Java SE 8?Differences between Iterator and Spliterator in Java SE 8?
Spliterator stands for Splitable Iterator. It is newly introduced by Oracle Corporation as part Java SE 8.
Like Iterator and ListIterator, It is also one of the Iterator interface.

S.NO.
SPLITERATOR
ITERATOR
1
It is introduced in Java SE 8.
It is available since Java 1.2.
2
Splitable Iterator
Non-Splitable Iterator
3
It is used in Stream API.
It is used for Collection API.
4
It uses Internal Iteration concept to iterate Streams.
It uses External Iteration concept to iterate Collections.
5
We can use Spliterator to iterate Streams in Parallel and Sequential order.
We can use Spliterator to iterate Collections only in Sequential order.
6
We can get Spliterator by calling spliterator() method on Stream Object.
We can get Iterator by calling iterator() method on Collection Object.
7
Important Method: tryAdvance()
Important Methods: next(), hasNext()



Which statements are true?
A.     Cohesion is the OO principle most closely associated with the hiding implementation details.
B.     Cohesion is the OO principle most closely associated with making sure that classes know about other classes only through the API.
C.    Cohesion is the OO principle most closely associated with making sure that class is designed with a single, well focused purpose.
D.     Cohesion is the OO principle most closely associated with allowing a single object to be seen as having many type.


Below example shows the visibility of method through their respective class reference.
class ParentTest {
 void getMethodOne() {
 }
}

public class Test extends ParentTest {
 void getMethodTwo() {
 }
 public static void main(String[] args) {
     ParentTest parentTest = new ParentTest();
     ParentTest test = new Test();
     Test test2 = new Test();
     test.getMethodTwo(); //Compiler error -
     //The method getMethodTwo() is undefined for the type ParentTest
     ((Test)test).getMethodTwo(); //test is typecast in Test that getMethodTwo() will be visible through
     //with Test refernece.
 }
}




Select correct option from below statement
1)     ClassA has a ClassD
2)     Method in ClassA use public methods in ClassB
3)     Method in ClassC use public methods in ClassA
4)     Method in ClassA use public variables in ClassB
Choose correct options:-
a)      ClassD has low cohesion.
b)     ClassA has weak encapsulation.
c)    ClassB has weak encapsulation.
d)     ClassB has strong encapsulation.
e)     ClassC is tightly coupled to ClassA



What is the O/P of below code:-

public class Test {

     public static void main(String... args) {
           Integer i = 34;
           long l = 34;
           int j = 34;
           if (i.equals(l))
                System.out.println(true);
           else
                System.out.println(false);
           if (i.equals(j))
                System.out.println(true);
           else
                System.out.println(false);
     }
}
O\P: - false
 True

Analysis:- int wrapped to Integer object so second comparison return true but Long and Integer are different object so condition failed in equals implementation equals method check the instance comparison
if(!(value instanceof Test))
     return false;



What is the O/P of below java code?

public class Test {
 public static void main(String... args) {
     System.out.println(getValue());
 }
 private static int getValue(){
     try {
           int value = 5/0;
           System.out.println(value);
           return 1;
     } catch (ArithmeticException arithmeticException) {
           return 2;
       } finally { //compiler warning -- finally block does not complete normally
           return 3;
     }
 }
}


In above java code finally block get executed with compiler warning as “”finally block does not complete normally and the output of above java code will be 3.
So we can see the finally block get executed in all the situation whether an exception occurred or not and will return 3.
So only condition when it will not execute is system.exit() method get called.


What will happen if we don’t override Thread class run() method?

Default code of run method of Thread class is as follows:-
private Runnable target;
public void run() {
    if (target != null) {
        target.run();
    }
}

Here target is set on thread initialization through runnable interface but if we create a thread without overriding the run () method it will do nothing as target will be null.


What is the output of below code?

public class Test {
     public static void main(String... args) {
           System.out.println(getValue(null));
     }
    
     private static String getValue(String value) {
           return "hello1";
     }
    
     private static String getValue(Object value) {
           return "hello2";
     }
}
In above code when we pass getValue(null),  it will print hello1 as string overloaded method will executed.


What is the output of below code?

public class Test {
     public static void main(String... args) {
           Test t= new Test();
/*line 4*/     System.out.println(t.getValue(null));//The method getValue(String) is ambiguous for the type Test
     }
    
     public String getValue(String value) {
           return "hello1";
     }
    
     public String getValue(StringBuffer value) {
           return "hello2";
     }
}
In above there will be a compiler error for method ambiguity at line no 4.


What is the output of below code?

import java.util.ArrayList;
import java.util.List;

public class Test {
     public static void main(String... args) {
           Test t= new Test();
           List<Integer> list = new ArrayList<>();
           System.out.println(t.getObjectValue(list)); //line 10
           System.out.println(t.getAnyValue(list));  //line 11
     }
    
     public String getObjectValue(List<Object> val) {
           return "hello1";
     }
    
     public String getAnyValue(List<?> val) {
           return "hello2";
     }
}
There will be a compiler error at line no 10 as getObjectValue(List<Object> val) will accept only list of object type, but getAnyValue(List<?> val) method will accept anything so there will not be any error on line 11.


What is the output of below code?

public class Test {
 public static void main(String... args) {

     float f1 = 2.3f;
     float[][] f2 = { { 42.0f }, { 1.7f, 2.3f }, { 2.6f, 2.7f } };
     float[] f3 = { 2.7f };
     Long x = 42L;
     //if (f1 == f2) // Copiler error -- Incompatible operand types float and float[][]
//              { System.out.println("true"); }
     if (f1 == f2[2][1]) {
           System.out.println("f1 == f2[2][1] -- true");
     }
     if (x == f2[0][0]) {
           System.out.println("x == f2[0][0] -- true");
     }
     //if (f1 == f2[1,1]) // Copiler error -- Incompatible operand types float and float[]
//             { System.out.println("true"); }
     if (f3 == f2[2]) {
           System.out.println("f3 == f2[2] -- true");
     }
 }
}
Output: x == f2[0][0] – true



What is the output of below code?

public class Test {
 public static void main(String... args) {
     String s = "";
     Boolean b1 = true;
     Boolean b2 = false;
if ((b2 = false) | (21%5) > 2) s += "x";  //false line 6
     if ((b1 || (b2 = true)))    s += "y";    // line 7
     if (b2 == true)                   s += "z";  // false line 8
     System.out.println(s);
 }
}

Output: y

Analysis: - in above code line no 6 (b2=false) -> false and (21%5=1>2) -> false, line no 7 b1 = true and b = true is true so s will be x and condition in line no 8 is again false. So the final output is y.


What is the output of below code?

public class Test {
 public static void main(String... args) {
     int mask = 0;
     int count = 0;
     if (((5 < 7) || (++count < 10) /* warning -- dead code*/) | mask++ < 10) // mask will be ++ and value will be 1
           mask = mask + 1; // mask will be 2
     if ((6 > 8) ^ false)
           mask = mask + 10; // warning -- dead code
     if (!(mask > 1) && ++count > 1)
           mask = mask + 100;
     System.out.println(mask + " " + count);
 }
}

Output: - 2 0


What is the output of below code?

public class Test {

public static void main(String[] args) {
     int[] ia = { 1, 3, 5, 7, 9 };
     for (int x : ia) {
         for (int j = 0; j < 3; j++) {
           if (x > 4 && x < 8)
            continue; // will be continued for x = 5, 7;
           System.out.println(" " + x); // this will be executed for 1, 3, 9;
           if (j == 1)
                break; // inner loop will be terminated for j = 1
           continue; // it will continue for j = 1 and 2
           }
           continue;
     }
  }
}

Output: -
 1
 1
 3
 3
 9
 9


What is the output of below code?

public class Test {

public static void main(String[] args) {
     foreach: for (int j = 0; j < 5; j++) {
     for (int k = 0; k < 3; k++) {
     System.out.println(" " + j);
     if (j == 3 && k == 1) // for j = 3 and k = 1 external foreach loop will break;
           break foreach;
     if (j == 0 || j == 2) // it will break the inner loop for j = 0, 2
           break;
     }
   }
 }
}
Output:
0
1
1
1
2
3
3




Find The First Non Repeated Character of A String?

The best solution of above problem is iterate the string and put the character into a LinkedHashMap to maintain insertion as key and occurrence as value than iterate the map to get the first key with occurrence one.
Use simple HashMap to store the value and iterate the map with the sequence of string character and get the char with occurrence one.

import java.util.HashMap;

public class FirstNonRepeatedCharTest {

public static void main(String[] args) {
     char c = firstNonRepeatedCharacter("java");
     System.out.println("The first non-repeated character is :  " + c);
}

public static Character firstNonRepeatedCharacter(String str) {
     HashMap<Character, Integer> dataMap = new HashMap<Character, Integer>();
     for (int i = 0; i < str.length(); i++) {
           char ch = str.charAt(i);
           dataMap.put(ch, dataMap.containsKey(ch) ? (dataMap.get(ch) + 1) : 1);
     }
     for (int i = 0; i < str.length(); i++) {
           char ch = str.charAt(i);
           if (dataMap.get(ch) == 1)
                return ch;
     }
     return null;
}
}

Output: - The first non-repeated character is:  j



What is linkage error in java?

Linkage error happened when class loader try to load a file which is already loaded.
Than it will give linkage error:
java.lang.LinkageError: loader constraint violation:

Class loader works the logic of delegation means before loading a class first it will check whether class is already loaded in parents or not, refer below link

So the class loaded ensure not to load the class which is already loaded.
Let’s see an example:-
Suppose class A is in A.Jar and class B in B.jar classB has dependency of classA,
Now Class A is lodeded in a proper way of classloader hierarchy and finally loaded by application class loader, now for class B loading started it check in application -> extension -> bootstrap class loader and loaded by extension class loader, now class B has a dependency of A so extension class loader will try to load the class A as well so it will check in extension and bootstrap class loader but it doesn’t have visibility to application class loader’s classes so it will try to load the class A as well and it will through linkage error.


String hashcode same for same same string reference

public class MainTest {
     public static void main(String[] args) {
           String str1 = new String("Manoj");
        String str2 = new String("Manoj");
        String str3 = new String("Kumar");

        System.out.println(str1.hashCode());
        //hascode for str1 will be same to str2 ass they are refeering to same object
        System.out.println(str1.hashCode() == str2.hashCode());
        System.out.println(str3.hashCode());
     }
}



There are eight houses in a row, there state is active (0) or inactive (1), a house will be inactive in next day if it’s both neighbor is either active or inactive otherwise it will active on next day.
The house on the edge should consider their blank neighbor is inactive.
Below is the Java code for this solution: -


import java.util.ArrayList;
import java.util.List;

public class MainTest {
public static void main(String... args) throws Exception {
// State of the houses
int[] states = {1,1,1,0,1,1,1,1};
//0 1 0 0 1 0 1 0
System.out.println(new MainTest().cellComplete(states, 2));
}
    
private List<Integer> cellComplete(int[] states, int days){
List<Integer> stateList = new ArrayList<>();
for(int curState : states) {
     stateList.add(curState);
}
int length = stateList.size();
while(days > 0) {
int index = 0;
for(int curState : states) {
     if(index == 0 && states[index+1] == 0) {
           stateList.set(index, 0);
     } else if (index == length-1 && states[index-1] == 0) {
           stateList.set(index, 0);
} else if (((index != 0) && (index != length-1)) && states[index-1] == states[index+1]) {
     stateList.set(index, 0);
     } else {
     stateList.set(index, 1);
     }
     index++;
}
          
// update state array for next day
int count = 0;
for(Integer val : stateList) {
states[count] = val;
count++;
}
days--;
}
return stateList;
}
}


Find the greatest common divisor for given n number
public class Test {
public static void main(String[] args) {
// There are an array with N number find the
int[] arr = { 2, 3, 4, 5, 6 };
new Test().generalizedGCD(5, arr);
}

public int generalizedGCD(int numint[] arr) {
int GCD = 1;
boolean flag = true;
for (int index = 1; index < arr[num - 1]; index++) {
       for (int count = 0; count < numcount++) {
              if (arr[count] % index != 0) {
                     flag = false;
                     break;
              }
       }
      
       if(flag) {
              GCD = index;
       }
}
return GCD;
}
}
public class Test {
public static void main(String[] args) {
// There are an array with N number find the
int[] arr = { 2, 3, 4, 5, 6 };
new Test().generalizedGCD(5, arr);
}

public int generalizedGCD(int num, int[] arr) {
int GCD = 1;
boolean flag = true;
for (int index = 1; index < arr[num - 1]; index++) {
     for (int count = 0; count < num; count++) {
           if (arr[count] % index != 0) {
                flag = false;
                break;
           }
     }
    
     if(flag) {
           GCD = index;
     }
}
return GCD;
}
}



ClassNotFoundException vs NoClassDefFoundError

ClassNotFoundException and NoClassDefFoundError occurs at runtime, due to class path error.

ClassNotFoundException occurs when class loaded at runtime using Class.forName() or loadClass() methods and requested classes are not found in classpath while NoClassDefFoundError occurs when class was present during compile time but class was not present during runtime

1 comment: