Core Java Interview Questions & Answers


Core Java

Basics


Can a top-level class be private or protected?
Top level classes in java can’t be private or protected, but inner classes in java can. The reason for not making a top-level class as private is very obvious, because nobody can see a private class and thus they cannot use it

Is it possible to make array volatile in Java?
Yes, it is possible to make an array volatile in Java, but only the reference which is pointing to an array, by reassigning it

What is a.hashCode() used for? How is it related to a.equals(b)?
According to the Java specification, two objects which are identical to each other using equals() method needs to have the same hash code

What is a compile time constant in Java? What is the risk of using it?
Answer: Public static final variables are also known as the compile time constant, the public is optional there. They are substituted with actual values at compile time because compiler recognizes their value up-front, and also recognize that it cannot be altered during runtime.
One of the issues is that if you choose to use a public static final variable from in-house or a third party library, and their value changed later, then your client will still be using the old value even after you deploy a new version of JARs.

Explain Liskov Substitution Principle.
According to the Liskov Substitution Principle, Subtypes must be appropriate for super type i.e. methods or functions which use super class type must be able to work with object of subclass without issues.

What is double checked locking in Singleton?
Singleton means we can create only one instance of that class
Rules:
·         Create Singleton class Object make it as PRIVATE
·         Create PRIVATE constructor
·         Every Singleton class contains at least one factory method
class Student {
    private static Student st;
    private Student() {
        System.out.println("OBJECET Created FIRST TIME");
    }
    public static Student getObject() {
        if (st == null) {
            st = new Student();
        } else {
            System.out.println("OBJECET ALREDAY CREATED");
        }
        return st;
    }
}

public class Singleton {
    public static void main(String[] args) {
        Student s1 = Student.getObject();
        Student s2 = Student.getObject();
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
    }
}

Double checked locking in Singleton means, at any cost only one instance is created in multi-threaded environment.
In this case at null checking make Block as Synchronized.


public
static Singleton getInstanceDC() {
        if (_instance == null) {                // Single Checked
            synchronized (Singleton.class) {
                if (_instance == null) {        // Double checked
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
}

 
When to use volatile variable in Java?
·         Volatile keyword is used with only variable in Java
·         it guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache.
·         So, we can use volatile to achieve synchronization because its guaranteed that all reader thread will see updated value of volatile variable once write operation completed

Difference between Serializable and Externalizable in Java?
Serialization is a default process of serializing or persisting any object's state in Java. It's triggered by implementing Serializable interface which is a marker interface (an interface without any method). uses default implementation to handle the object serialization process.
Externalizable is used to user defined serialization process and control default serialization process which is implemented by application.
Externalizable interface extends Serializable interface. It consists of two methods
// to read object from stream
void readExternal(ObjectInput in)

// to write object into stream
void writeExternal(ObjectOutput out)


Difference between static and dynamic binding in Java? (detailed answer)
This is usually asked as follow-up of previous question, static binding is related to overloaded method and dynamic binding is related to overridden method. Method like private, final and static are resolved using static binding at compile time but virtual methods which can be overridden are resolved using dynamic binding at runtime.




















JVM Internals and Garbage Collection

Difference Between JVM & HotSpot VM
JVM : is a Specification, HotSpot : is a implementation of JVM.
HotSpot is an implementation of the JVM concept, originally developed by Sun and now owned by Oracle. There are other implementations of the JVM specification, like JRockitIBM J9, among many others.


How does WeakHashMap work?
WeakHashMap operates like a normal HashMap but uses WeakReference for keys. Meaning if the key object does not devise any reference then both key/value mapping will become appropriate for garbage collection.
How do you locate memory usage from a Java program? 
Answer: You can use memory related methods from java.lang.Runtime class to get the free memory, total memory and maximum heap memory in Java

What is ClassLoader in Java?
When a Java program is converted into .class file by Java compiler which is collection of byte code. ClassLoader is responsible to load that class file from file system, network or any other location
·         Bootstrap ClassLoader - JRE/lib/rt.jar
·         Extension ClassLoader - JRE/lib/ext or any directory denoted by java.ext.dirs
·         Application ClassLoader - CLASSPATH environment variable, -classpath or -cp option, Class-Path attribute of Manifest inside JAR file.

Java heap memory
When a Java program started Java Virtual Machine gets some memory from Operating System.
whenever we create an object using new operator or by any another means the object is allocated memory from Heap and When object dies or garbage collected, memory goes back to Heap space.
How to increase heap size in Java
Default size of Heap space in Java is 128MB on most of 32 bit Sun's JVM but its highly varies from JVM to JVM. change size of heap space by using JVM options -Xms and -Xmx. Xms denotes starting size of Heap while -Xmx denotes maximum size of Heap in Java.

Java Heap and Garbage Collection
As we know objects are created inside heap memory and Garbage Collection is a process which removes dead objects from Java Heap space and returns memory back to Heap in Java.
 For the sake of Garbage collection Heap is divided into three main regions named as New Generation, Old Generation, and Perm space
·         New Generation of Java Heap is part of Java Heap memory where a newly created object is stored,
·         Old Generation During the course of application many objects created and died but those remain live they got moved to Old Generation by Java Garbage collector thread
·         Perm space of Java Heap is where JVM stores Metadata about classes and methods, String pool and Class level details.

·         Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.

·         The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).

·         Neither finalization nor garbage collection is guaranteed.








Strings

1.What is immutable object? Can you write immutable object?
Don’t confuse over SingleTon class
Immutable classes are Java classes whose objects can not be modified once created. 
1.     Declare the class as final so it can’t be extended.
2.     Make all fields private & final so that direct access is not allowed & it’s values can be assigned only once..
3.     Initializeall the fields via a constructor
4.     Write getters only, not setters.
// An immutable class
public final class Student
{
    final String name;
    final int regNo;

    public Student(String name, int regNo)
    {
        this.name = name;
        this.regNo = regNo;
    }
    public String getName()
    {
        return name;
    }
    public int getRegNo()
    {
        return regNo;
    }
}

// Driver class
class Test
{
    public static void main(String args[])
    {
        Student s = new Student("ABC", 101);
        System.out.println(s.name);
        System.out.println(s.regNo);

        // Uncommenting below line causes error
        // s.regNo = 102;
    }
}



2.What is Singleton? Can you write critical section code for singleton?
A Singleton class is one which allows us to create only one object for JVM.
Rules:
·         Create Singleton class Object make it as PRIVATE
·         Create PRIVATE contrcutor
·         Every Singleton class contains at least one factory method
class Student {
private static Student st;
private Student() {
System.out.println("OBJECET Created FIRST TIME");
}

public static Student getObject() {
if (st == null) {
st = new Student();
} else {
System.out.println("OBJECET ALREDAY CREATED");
}
return st;
}
}

public class Singleton {
public static void main(String[] args) {
Student s1 = Student.getObject();
Student s2 = Student.getObject();
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}
In above code, it will create multiple instances of Singleton class if called by more than one thread parallel
Double checked locking of Singleton is a way to ensure only one instance of Singleton class is created through application life cycle.
This will bring us to double checked locking pattern, where only critical section of code is locked. Programmer call it double checked locking because there are two checks for _instance == null, one without locking and other with locking (inside synchronized) block. Here is how double checked locking looks like in Java
public staticSingleton getInstanceDC() {
        if (_instance == null) {                // Single Checked
            synchronized(Singleton.class) {
                if(_instance == null) {        // Double checked
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
}

How do you reverse a String in Java without using StringBuffer?
The Java library provides String Buffer and StringBuilder class with reverse() method, which can be used to reverse String in Java.

How to Print duplicate characters from String?
package prog;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;

public class RepreatedChar {
       public static void main(String[] args) {

              String a = "success";

              // 1.convert into char array
              char[] c= a.toCharArray();

              // 2.create Hashmap store key as character, count as value
              HashMapmap = new HashMap<>();
              for (char ch : c) {

                     // 3.Check if Map contains given Char as <key> or not
                     if (map.containsKey(ch)) {
                           // if their, get the value & increment it
                           int i = (int) map.get(ch);
                           i++;
                           // add updated value to it
                           map.put(ch, i);
                     } else {
                           // if not their , add key & value as 1
                           map.put(ch, 1);
                     }

              }
             
             
               Set  set =  map.entrySet();
               Iterator iterator = set.iterator() ;
               while(iterator.hasNext()) {
                     Map.Entryentry = (Entry) iterator.next();
                     System.out.println(entry.getKey()+" : "+entry.getValue());
                    
              }
               

       }
}
s : 3
c : 2
u : 1
e : 1


Reverse String in Java
1.     Get String length
2.     Iterate by using charAt() & append to new String
public class ReverseString {
public static void main(String[] args) {
  
   String s = "satyam";
   String rev="";
   int len = s.length();
  
   for(int i=(len-1);i>=0;i--){
         
          rev = rev+s.charAt(i);
   }
  
   System.out.println(rev);
}
}

Is String contains Number or not
public class RegEx {
       public static void main(String[] args) {
              // Regular expression in Java to check if String is number or not
              Pattern pattern = Pattern.compile(".*[^0-9].*");          
              String[] inputs = { "123", "-123", "123.12", "abcd123" };
              /* Matches m = pattern.match(input);
               * boolean ch = m.match();
               */
             
             

              for (String input : inputs) {
              System.out.println("does " + input + " is number : " + !pattern.matcher(input).matches());
              }

              // Regular expression in java to check if String is 6 digit number or  not
              String[] numbers = { "123", "1234", "123.12", "abcd123", "123456" };
              Pattern digitPattern = Pattern.compile("\\d{6}");
              // Pattern digitPattern = Pattern.compile("\\d\\d\\d\\d\\d\\d");

              for (String number : numbers) {
                     System.out.println("does " + number + " is 6 digit number : "+ digitPattern.matcher(number).matches());
              }
       }
}




Reverse Words in a String
public class RevWords {
       public static void main(String[] args) {

              // using s.split("\\s");
              String s = "My name is Satya";
              String words[] = s.split("\\s");
              String rev = "";
              int len = words.length;
              for (int i = (len- 1); i >= 0; i--) {
                     rev = rev + words[i];
              }
              System.out.println(rev);

              // using Collections.reverse(str)
              List<String> word = Arrays.asList(s.split("\\s"));
              Collections.reverse(word);
              System.out.println(word);
       }
}


















Exception Handling

What will happen if you put System.exit(0) on try or catch block?
By Calling System.exit(0) in try or catch block, its stops execution & throws SecurityException.
·         If Sysytem.exit(0) NOT throws security exception then finally block Won’t be executed
·         But, if System.exit(0) throws security exception then finally block will be executed.

What happens if we put return statement on try/catch? Will finally block execute?
Yes, finally block will execute even if you put a return statement in the try block or catch block.
try {
    //try block
    ...
    return success;
}
catch (Exception ex) {
    //catch block
    .....
    return failure;
}
finally {
    System.out.println("Inside finally");
}
The answer is yes. finally block will execute. The only case where it will not execute is when it encounters System.exit().


What happens when a finally block has a return statement?
Finally block overrides the value returned by try and catch blocks.
public static int myTestingFuncn(){
  try{
     ....
     return 5;
  }
  finally {
     ....
     return 19;
   }
}
This program would return value 19 since the value returned by try has been overridden by finally.

Why do you think Checked Exception exists in Java, since we can also convey error using RuntimeException?
Most of checked exceptions are in java.io package, which make sense because if you request any system resource and its not available, than a robust program must be able to handle that situation gracefully.
By declaring IOException as checked Exception, Java ensures that your provide that gracefully exception handling. Another possible reason could be to ensuring that system resources like file descriptors, which are limited in numbers, should be released as soon as you are done with that using catch or finally block
 
Have you faced OutOfMemoryError in Java? How did you solved that?
OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when it ran out of memory in the heap.
An easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options "-Xmx512M", this will immediately solve your OutOfMemoryError.












Threads

How do you ensure that N thread can access N resources without deadlock
Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. 

What is busy spin, and why should you use it?
Busy spinning is a waiting strategy in which one thread loop continuously  to check certain condition and waiting for other thread to change this condition to break the loop without releasing CPU so that waiting thread can proceeds its work further

What’s the difference between Callable and Runnable?
Both of these are interfaces used to carry out task to be executed by a thread. The main difference between the two interfaces is that
·         Callable can return a value, while Runnable cannot.
·         Callable can throw a checked exception, while Runnable cannot.
·         Runnable has been around since Java 1.0, while Callable was introduced as part of Java 1.5.
The Callable interface is a generic interface containing a single call() method – which returns a generic value V:
public interface Callable<V> {
    V call() throws Exception;
}
class CallableExample implements Callable
{

    public Object call() throws Exception
    {
        Random generator = new Random();
        Integer randomNumber = generator.nextInt(5);
        Thread.sleep(randomNumber * 1000);

        return randomNumber;
    }
}

What is false sharing in the context of multi-threading?
 false sharing is one of the well-known performance issues on multi-core systems, where each process has its local cache.
False sharing is very hard to detect because the thread may be accessing completely different global variables that happen to be relatively close together in memory. Like many concurrency issues, the primary way to avoid false sharing is careful code review and aligning your data structure with the size of a cache line
Object level and Class level locks in Java
Object level lock : Every object in java has a unique lock. Whenever we are using synchronized keyword, then only lock concept will come in the picture. If a thread wants to execute synchronized method on the given object. First, it has to get lock of that object. Once thread got the lock then it is allowed to execute any synchronized method on that object. Once method execution completes automatically thread releases the lock. Acquiring and release lock internally is taken care by JVM and programmer is not responsible for these activities. Lets have a look on the below program to understand the object level lock:
class Geek implements Runnable {
    public void run()
    {
        Lock();
    }
    public void Lock()
    {
        System.out.println(Thread.currentThread().getName());
        synchronized(this)
        {
            System.out.println("in block "
                + Thread.currentThread().getName());
            System.out.println("in block " +
                Thread.currentThread().getName() + " end");
        }
    }

    public static void main(String[] args)
    {
        Geek g = new Geek();
        Thread t1 = new Thread(g);
        Thread t2 = new Thread(g);
        Geek g1 = new Geek();
        Thread t3 = new Thread(g1);
        t1.setName("t1");
        t2.setName("t2");
        t3.setName("t3");
        t1.start();
        t2.start();
        t3.start();
    }
}
Run on IDE
Output:
t1
in block t1
in block t1 end
t2
in block t2
in block t2 end
t3
in block t3
in block t3 end
Class level lock : Every class in java has a unique lock which is nothing but class level lock. If a thread wants to execute a static synchronized method, then thread requires class level lock. Once a thread got the class level lock, then it is allowed to execute any static synchronized method of that class. Once method execution completes automatically thread releases the lock. Lets look on the below program for better understanding:

// Java program to illustrate class level lock
class Geek implements Runnable {
    public void run()
    {
        Lock();
    }

    public void Lock()
    {
        System.out.println(Thread.currentThread().getName());
        synchronized(Geek.class)
        {
            System.out.println("in block "
                + Thread.currentThread().getName());
            System.out.println("in block "
                + Thread.currentThread().getName() + " end");
        }
    }

    public static void main(String[] args)
    {
        Geek g1 = new Geek();
        Thread t1 = new Thread(g1);
        Thread t2 = new Thread(g1);
        Geek g2 = new Geek();
        Thread t3 = new Thread(g2);
        t1.setName("t1");
        t2.setName("t2");
        t3.setName("t3");
        t1.start();
        t2.start();
        t3.start();
    }
}

Producer-Consumer solution using threads in Java
·         The producer’s job is to generate data, put it into the buffer, and start again.
·         same time, the consumer is consuming the data (i.e. removing it from the buffer), one piece at a time.
·         producer won’t try to add data into the buffer if it’s full & consumer won’t try to remove data from an empty buffer
classProducer extendsThread {

        List buffer;
        int maxsize;

        public Producer(Listbuffer, int maxsize) {
                this.buffer = buffer;
                this.maxsize = maxsize;
        }

        @Override
        public void run() {
        int i = 1;
          while (true) {
             synchronized (buffer) {
                try {
                        if (buffer.size() == maxsize) {
                        System.out.println("Maximum Size Reached, wait until consume");
                        buffer.wait();
                        } else {
                        buffer.add(i++);
                        System.out.println(i + " : Produced, notify wating COnsumer Thread");
                        buffer.notifyAll();

                        }
                } catch(InterruptedException e) {
                                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                }

                }

        }

}

classConsumer extendsThread {

        List buffer;
        int maxsize;

        public Consumer(Listbuffer, int maxsize) {
                this.buffer = buffer;
                this.maxsize = maxsize;
        }

        @Override
        public void run() {

        while (true) {
                try {
                synchronized (buffer) {
                if (buffer.isEmpty()) {
                        System.out.println("Consumer : Buffer Empty, wait untill produce");
                        buffer.wait();
                        } else {
                        Object ob = buffer.remove(0);
                System.out.println(ob + " : Removed, notify Producer waiting for Removing for maxsize");
                buffer.notifyAll();
                        }
                }
                } catch (Exception e) {
                                // TODO: handle exception
                }

        }

   }

}

publicclassProducerConsumer {

        public static void main(String[] args) {

                Listbuffer = new LinkedList<>();
                Producer producer = new Producer(buffer, 10);
                Consumer consumer = new Consumer(buffer, 10);
                producer.start();
                consumer.start();

        }

}
28054 : Produced, notify wating COnsumer Thread
28055 : Produced, notify wating COnsumer Thread
28056 : Produced, notify wating COnsumer Thread
28057 : Produced, notify wating COnsumer Thread
28058 : Produced, notify wating COnsumer Thread
28059 : Produced, notify wating COnsumer Thread
28060 : Produced, notify wating COnsumer Thread
Maximum Size Reached, wait until consume
28050 : Removed, notify Producer waiting for Removing for maxsize
28051 : Removed, notify Producer waiting for Removing for maxsize
28052 : Removed, notify Producer waiting for Removing for maxsize
28053 : Removed, notify Producer waiting for Removing for maxsize
28054 : Removed, notify Producer waiting for Removing for maxsize
28055 : Removed, notify Producer waiting for Removing for maxsize
28056 : Removed, notify Producer waiting for Removing for maxsize
28057 : Removed, notify Producer waiting for Removing for maxsize
28058 : Removed, notify Producer waiting for Removing for maxsize
28059 : Removed, notify Producer waiting for Removing for maxsize
Consumer : Buffer Empty, wait untill produce



Thread. yield ()
yield() method: Theoretically, to ‘yield’ means to let go, to give up, to surrender. A yielding thread tells the virtual machine that it’s willing to let other threads be scheduled in its place.
This indicates that it’s not doing something too critical. Note that it’s only a hint, though, and not guaranteed to have any effect at all.
·         Yield is a Static method and Native too.
·         Yield tells the currently executing thread to give a chance to the threads that have equal priority in the Thread Pool.
·         There is no guarantee that Yield will make the currently executing thread to runnable state immediately.
·         It can only make a thread from Running State to Runnable State, not in wait or blocked state.

What do you understand about Thread Priority?
Every thread has a priority, usually higher priority thread gets precedence in execution but it depends on Thread Scheduler implementation that is OS dependent. We can specify the priority of thread but it doesn’t guarantee that higher priority thread will get executed before lower priority thread.
How can we make sure main() is the last thread to finish in Java Program?
We can use Thread join() method to make sure all the threads created by the program is dead before finishing the main function.
Why wait(), notify() and notifyAll() methods have to be called from synchronized method or block?
When a Thread calls wait() on any Object, it must have the monitor on the Object that it will leave and goes in wait state until any other thread call notify() on this Object. Similarly when a thread calls notify() on any Object, it leaves the monitor on the Object and other waiting threads can get the monitor on the Object. Since all these methods require Thread to have the Object monitor, that can be achieved only by synchronization, they need to be called from synchronized method or block.
How can we achieve thread safety in Java?
There are several ways to achieve thread safety in java – synchronization, atomic concurrent classes, implementing concurrent Lock interface, using volatile keyword, using immutable classes and Thread safe classes.

What is volatile keyword in Java
When we use volatile keyword with a variable, all the threads read it’s value directly from the memory and don’t cache it. This makes sure that the value read is the same as in the memory.
What is ThreadLocal?
Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
What is Java Thread Dump, How can we get Java Thread dump of a Program?
Thread dump is list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump – Using Profiler, Kill -3 command, jstack tool etc. I prefer jstack tool to generate thread dump of a program because it’s easy to use and comes with JDK installation
What is atomic operation? What are atomic classes in Java Concurrency API?
Atomic operations are performed in a single unit of task .int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result.
To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomically without usage of Synchronization
What is BlockingQueue? implement Producer-Consumer using Blocking Queue?
·         java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
·         BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
·         BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.
·         BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem.
Check this post for producer-consumer problem implementation using BlockingQueue.

What is Executors Class?
Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.
Executors class can be used to easily create Thread Pool in java, also this is the only class supporting execution of Callable implementations.
What happens when an Exception occurs in a thread?
Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException() method, passing the thread and the exception as arguments.

Why wait, notify and notifyAll are not inside thread class?
One reason which is obvious is that Java provides lock at object level not at thread level.

How do you check if a Thread holds a lock or not?
Boolean Thread.holdsLock(Obj)








Collections

1. What is the difference between ArrayList and Vector ?
Synchronization and Thread-Safe
Vector is  synchronized while ArrayList is not synchronized 
Performance
Vector is slow as it is thread safe . In comparison ArrayList is fast
Automatic Increase in Capacity
A Vector defaults to doubling size ,ArrayList ,it increases its Array size by (curr.capcity*3)/2  + 1 
Enumeration & iterator
Vector is the only other class which uses both Enumeration and Iterator .While ArrayList can only use Iterator for traversing an ArrayList
Is it possible for two unequal objects to have the same hashcode?
Yes, two unequal objects can have the same hashcode. This is why collision can occur in hashmap. The equal hashcode contract only says that two equal objects must have the identical hashcode, but there is no indication to say anything about the unequal object.

Differences between HashMap and HashTable in Java.
1. HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized.  
2. HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value.

Which two method you need to implement for key Object in HashMap ?
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.
 What will happen if we put a key object in a HashMap which is already there ?
if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys

difference between Iterator and Enumeration in Java?



















References





Post a Comment

Thank You

Previous Post Next Post