Showing posts sorted by date for query how-hashmap-works-in-java. Sort by relevance Show all posts
Showing posts sorted by date for query how-hashmap-works-in-java. Sort by relevance Show all posts

Wednesday, December 11, 2019

Top 21 Oftentimes Asked Coffee Interview Questions Answers

If yous convey been to couplet of Java interviews hence yous know that at that spot are roughly questions which choke on repeating e.g. difference betwixt == as well as equals() method and may of it's pop cousins similar HashMap vs Hashtable, ArrayList vs LinkedList, departure betwixt equals() as well as hashCode(), or departure betwixt Comparator as well as Comparable inward Java. I telephone telephone them often asked Java interview questions, as well as I propose every Java developer to brand a listing of them for their ain reference as well as revision. I am certain many Java programmer already has such listing of questions handy, if non this is a expert fourth dimension to honor as well as brand your ain list. These are the questions which yous precisely can't afford to miss, especially at freshers level. They seem at diverse phase of Java interviews. Most probable yous volition run across them on telephonic round, where Interviewer precisely desire to filter candidates betwixt who knows Java as well as who doesn't.

Good matter close them is that they are hence mutual that everyone knows close it. Though for freshers it could hold out picayune difficult. but equally your sense grows these often asked questions acquire much easier to answer.

Some programmers besides prefer to collect often asked Java questions based upon topics e.g. mutual questions from threads, strings, collections and other pop Java interview topics, roughly of them are already shared yesteryear me. In this list, I am sharing roughly of the most often asked questions from Java interviews.

By the way, when yous hold off the list, yous volition run across roughly of the classics are missing e.g. difference betwixt String as well as StringBuffer, but at that spot are many similar that, as well as that is job for yous to collect equally many equally possible as well as choke on them handy to avoid searching from them precisely earlier interview. I volition besides add together roughly to a greater extent than questions on this listing but for straightaway let's start alongside these 21 questions.




Frequently Asked Core Java Question as well as Answer

 If yous convey been to couplet of Java interviews hence yous know that at that spot are roughly questions Top 21 Frequently Asked Java Interview Questions AnswersHere is my listing of roughly of the most mutual questions from Java interviews. You volition mostly run across these questions on telephonic circular of your interview, but it is besides asked a lot of fourth dimension during confront to confront interviews. It's non express to whatever particular fellowship equally well, inward fact all major information technology companies inward Republic of Republic of India e.g. TCS, CTS, Infosys, Tech Mahindra, HCL, Oracle Financial Services, as well as major investment banks similar Barclays Capital, Morgan Stanley, Goldman Sachs, Credit Suisse asked these form of fact based query on their Java recruitment drives. By the way, roughly questions are actually easy, as well as roughly are existent tough, hence it's mixed of both, but 1 matter is common, they are the most often asked questions from Java interviews.


1)  How Java achieves platform independence?
Answer : When nosotros country Java is platform independent which agency Java programs are non theme on whatever platform, architecture or operating organization similar windows or Linux. Java arrive at this yesteryear using Java virtual machine, when Java programs are compiled they are converted to .class file which is collection of byte code as well as straight understandable  by JVM. So the same Java plan tin dismiss run on whatever operating organization alone JVM tin dismiss differ according to OS but all JVM tin dismiss sympathize converted byte code that's how Java arrive at platform independence. For a to a greater extent than detailed reply of this question, run across here.


2)  What is ClassLoader inward Java?
Answer : This was 1 of advanced query few years ago, but inward bridge of 2 to 3 years, this has acquire really common. When a Java plan is converted into .class file yesteryear Java compiler  which is collection of byte code  class loader is responsible to charge that degree file from file system,network or whatever other location. This degree loader is nix but besides a degree from which place they are loading the degree according to that degree loaders are 3 types :
  1.Bootstrap
  2.Extension
  3.System degree loader .
to larn to a greater extent than classloaders inward Java, run across my article how classloader industrial plant inward Java.


3)  Write a Java plan to depository fiscal establishment check if a pose out is Even or Odd?
Answer : This query is non especially related to Java as well as besides asked on other programming interviews e.g. C, C++ or C#. I convey included this inward my listing of often asked questions from Java interviews because I convey seen it to a greater extent than often than not.

import java.util.Scanner;  class TestEvenOdd {  public static void main(String arg[]){    int num;    //Read a number    Scanner input = new Scanner(System.in);    System.out.println("Enter a pose out to depository fiscal establishment check its Even or Odd");    num = input.nextInt();    // Conditional operator    System.out.println((num%2)==0 ? "even number":"odd number");   } }


4)  Difference betwixt ArrayList as well as HashSet inward Java?
Answer : If I country that this is 1 of the most most often asked query to Java programmers, hence it would non hold out wrong. Along alongside questions similar ArrayList vs LinkedList as well as ArrayList vs Vector, this query is most mutual on diverse Java interviews. Here are roughly of import differences betwixt these 2 classes :

  1. ArrayList implements List interface piece HashSet implements Set interface inward Java.
  2. ArrayList is an ordered collection as well as maintains insertion lodge of elements piece HashSet is an unordered collection as well as doesn't hold whatever order.
  3. ArrayList allow duplicates piece HashSet doesn't allow duplicates.
  4. ArrayList is backed yesteryear an Array piece HashSet is backed yesteryear an HashMap instance.
  5. One to a greater extent than departure betwixt HashSet as well as ArrayList is that its index based yous tin dismiss think object yesteryear calling get(index) or withdraw objects yesteryear calling remove(index) piece HashSet is completely object based. HashSet besides doesn't render get() method.



5)  What is double checked locking inward Singleton?
Answer : Interviewer volition never halt quest this question. It's woman nurture of all often asked query inward Java. Singleton agency nosotros tin dismiss exercise alone 1 instance of that class,in term of singleton DCL is the way to  ensure that at whatever toll alone  one instance is created inward multi-threaded surroundings its possible that simultaneously 2 thread trying to exercise instance of singleton degree inward that province of affairs nosotros cant certain that alone 1 instance is created hence avoid this province of affairs using double checked locking yesteryear using synchronized block where nosotros creating the object.

Code Example :
class SingletonClass {   private DCL dcl = null;   public DCL getDCL() {     if (dcl == null) {       synchronized {         if (dcl == null)           dcl = new DCL();       }     }     return dcl;   } }
To larn to a greater extent than close why double checked locking was broken earlier Java 1.5, run across this article.

6)  How exercise yous exercise thread-safe Singleton inward Java?
Answer : This is usually follow-up of previous Java question. There are to a greater extent than than 1 ways to exercise it. You tin dismiss  create thread security Singleton degree inward Java yesteryear creating the 1 as well as alone instance during degree loading. static fields are initialized during degree loading as well as Classloader volition guarantee that instance volition non hold out visible until its fully created.


7)  When to utilisation volatile variable inward Java?
Answer : Volatile keyword is used alongside alone variable  in Java as well as it guarantees that value of volatile variable volition ever hold out read from principal retentiveness as well as non from Thread's local cache. So nosotros tin dismiss utilisation volatile to arrive at synchronization because its guaranteed that all reader thread volition run across updated value of volatile variable 1 time write performance completed, without volatile keyword dissimilar reader thread may run across dissimilar values. Volatile modifier besides helps to preclude reordering of code yesteryear compiler as well as offering visibility guarantee yesteryear happens-before relationship. See this article to larn to a greater extent than close volatile inward Java.


8)  When to utilisation transient variable inward Java?
Answer : Transient inward Java is  used to betoken that the variable should non hold out serialized. Serialization is a procedure of saving an object's land inward Java. When nosotros desire to persist as well as object's land yesteryear default all instance variables inward the object is stored. In roughly cases, if yous desire to avoid persisting roughly variables because nosotros don’t convey the necessity to transfer across the network. So, declare those variables equally transient. If the variable is declared equally transient, hence it volition non hold out persisted. This is the principal purpose of the transient keyword, to larn to a greater extent than close transient variable inward Java, run across this tutorial.


9)  Difference betwixt transient as well as volatile variable inward Java?
Answer : This is 1 time again follow-up of previous 2 Java questions. You volition run across this query on laissez passer on 10 on whatever listing of Java often asked question. Here are roughly of the of import departure betwixt them.
Transient variable : transient keyword is used alongside those instance variable which volition non participate inward serialization process.we cannot utilisation static alongside transient variable equally they are purpose of instance variable.
Volatile variable : volatile keyword is used alongside alone variable  in Java as well as it guarantees that value of volatile variable volition ever hold out read from principal retentiveness as well as non from Thread's local cache, it tin dismiss hold out static.
to larn to a greater extent than differences as well as reply this query inward detail, run across here.


10) Difference betwixt Serializable as well as Externalizable inward Java?
Answer : If I country this is 1 of the most often asked Java query on both face-to-face as well as telephonic interview hence it would hold out an exaggeration. Serialization is a default procedure of  serializing or persisting  any object's land inward Java. It's triggered yesteryear implementing Serializable interface which is a mark interface (an interface without whatever method). While Externalizable is used to customize as well as command default serialization procedure which is implemented yesteryear application. Main departure betwixt these 2 is that Externalizable interface provides consummate command to the degree implementing the interface whereas Serializable interface unremarkably uses default implementation to grip the object serialization process.
Externalizable interface has 2 method writeExternal(ObjectOutput) as well as readExternal(ObjectInput) method which are used to grip customized object serialize procedure as well as inward damage of performance its expert because everything is nether control. to larn to a greater extent than close this classical question, run across this answer equally well.


11) Can nosotros override somebody method inward Java?
Answer : No, nosotros cannot override somebody methods inward Java equally if nosotros declare whatever variable ,method equally somebody that variable or method volition hold out visible for that degree alone as well as besides if nosotros declare whatever method equally somebody than they are bonded alongside degree at compile fourth dimension non inward run fourth dimension hence nosotros cant reference those method using whatever object hence nosotros cannot override somebody method inward Java.


12) Difference betwixt Hashtable as well as HashMap inward Java?
Answer : This is roughly other often asked query from Java interview. Main departure betwixt HaspMap as well as Hashtable are next :

  • HashMap allows zero values equally fundamental as well as value whereas Hashtable doesn't allow nulls.
  • Hashtable is thread-safe as well as tin dismiss hold out shared betwixt multiple threads whereas HashMap cannot hold out shared betwixt multiple threads without proper synchronization.
  • Because of synchronization, Hashtable is considerably slower than HashMap, fifty-fifty inward illustration of unmarried threaded application.
  • Hashtable is a legacy class, which was previously implemented Dictionary interface. It was afterwards retrofitted into Collection framework yesteryear implementing Map interface. On the other hand, HashMap was purpose of framework from it's inception.
  • You tin dismiss besides brand your HashMap thread-safe yesteryear using Collections.synchronizedMap() method. It's performance is similar to Hashtable.
See hither to larn to a greater extent than as well as sympathize when to utilisation Hashtable as well as HashMap inward Java. 



13) Difference betwixt List as well as Set inward Java?
Answer : One to a greater extent than classic often asked question. List as well as laid both are really useful interfaces of  collections inward Java as well as  difference betwixt these 2 is listing allows duplicate chemical cistron but laid don't allows duplicate elements roughly other departure is listing hold the insertion lodge of chemical cistron but laid is unordered collection .list tin dismiss convey many zero objects but laid permit alone 1 zero element. This query is roughly fourth dimension besides asked equally departure betwixt Map, List as well as Set to arrive to a greater extent than comprehensive equally those 3 are major information construction from Java's Collection framework. To reply that query run across this article.


14) Difference betwixt ArrayList as well as Vector inward Java
Answer : One to a greater extent than favourite of Java Interviewers, at that spot is hardly whatever interview of junior Java developers, on which this query doesn't appear. In 4 as well as v circular of interview, yous volition definitely going to run across this query inward roughly dot of time. Vector as well as ArrayList both implement the listing interface but principal departure betwixt these 2 is vector is synchronized as well as thread security but listing is non because of this listing is faster than vector.


15) Difference betwixt Hashtable as well as ConcurrentHashMap inward Java?
Answer : Both Hashtable as well as ConcurrentHashMap is used inward multi-threaded surroundings because both are therad-safe but principal departure is on performance Hashtable's performance acquire wretched if the size of Hashtable acquire large because it volition hold out locked for long fourth dimension during iteration but inward illustration of concurrent HaspMap  only specific purpose is locked because concurrent HaspMap industrial plant on sectionalisation as well as other thread tin dismiss access the chemical cistron without iteration to complete. To larn to a greater extent than close how ConcurrentHashMap achieves it's thread-safety, scalability using lock stripping as well as non blocking algorithm, run across this article equally well.


16) Which 2 methods yous volition override for an Object to hold out used equally Key inward HashMap?
Answer : equals() as well as hashCode() methods needs to hold out override for an object to hold out used equally fundamental inward HaspMap. In Map objects are stored equally fundamental as well as value.  put(key ,value) method is used to shop objects inward HashMap at this fourth dimension hashCode() method is used to calculate the hash-code of fundamental object as well as both fundamental as well as value object is stored equally map.entry.if 2 fundamental objects convey same hash-code hence alone value object is stored inward that same bucket place but equally a linked listing value is stored as well as if hash code is dissimilar hence roughly other bucket place is created. While retrieving get(key) method is used at this fourth dimension hash code of fundamental object is calculated as well as hence equals() method is called to compare value object. to larn to a greater extent than close how get() method of HashMap or Hashtable works, run across that article.


17) Difference betwixt hold off as well as slumber inward Java?
Answer:  Here are roughly of import differences betwixt hold off as well as slumber inward Java

  1. wait() method free the lock when thread is waiting but sleep() method concur the lock when thread is waiting.
  2. wait() is a instance method as well as slumber is a static method .
  3. wait method is ever called from synchronized block or method but for slumber at that spot is no such requirement.
  4. waiting thread tin dismiss hold out awake yesteryear calling notify() as well as notifyAll() piece sleeping thread tin dismiss non hold out awaken yesteryear calling notify method.
  5. wait method is status based piece sleep() method doesn't require whatever condition. It is precisely used to pose electrical current thread on sleep.
  6. wait() is defined inward java.lang.Object degree piece sleep() is defined inward java.lang.Thread class


18) Difference betwixt notify as well as notifyAll inward Java?
Answer : principal departure betwixt notify as well as notifyAll is notify method volition wake upwards  or notify alone 1 thread as well as notifyall volition notify all threads. If yous are certain that to a greater extent than than 1 thread is waiting on monitor as well as yous desire all of them to give equal lead chances to compete for CPU, utilisation notifyAll method. See here to a greater extent than differences betwixt notify vs notifyAll.


19) What is charge cistron of HashMap means?
Answer : HashMap's performance depends on 2 things offset initial capacity as well as minute charge cistron whenever nosotros exercise HashMap initial capacity pose out of bucket is created initially as well as charge cistron is criteria to determine when nosotros convey to increase the size of HashMap when its close to acquire full.


20) Difference betwixt PATH as well as Classpath inward Java?
Answer : PATH is a surroundings variable inward Java which is used to assist Java plan to compile as well as run.To laid the PATH variable nosotros convey to include JDK_HOME/bin directory inward PATH surroundings variable as well as besides nosotros cannot override this variable. On the other hand,  ClassPath variable is used yesteryear degree loader to locate as well as charge compiled Java codes stored inward .class file. We tin dismiss laid classpath nosotros demand to include all those directory where nosotros convey pose either our .class file or JAR file which is required yesteryear your Java application,also nosotros tin dismiss override this surroundings variable.


21) Difference betwixt extends Thread as well as implements Runnable inward Java
This is the 21st often asked query inward my list. You volition run across this query equally offset or minute on multi-threading topic. One of the principal dot to pose across piece answering this query is Java's multiple inheritance support. You cannot to a greater extent than than 1 class, but yous tin dismiss implement to a greater extent than than 1 interface. If yous extend Thread degree precisely to override run() method, yous lose might of extending roughly other class, piece inward illustration of Runnable, yous tin dismiss yet implement roughly other interface or roughly other class. One to a greater extent than departure is that Thread is abstraction of independent path of execution, piece Runnable is abstraction of independent task, which tin dismiss hold out executed yesteryear whatever thread. That's why it's ameliorate to implement Runnable than extending Thread degree inward Java. If yous similar to dig more, run across this answer.


That's all on this list of xx most often asked Java interview questions as well as answers. By the way, this is non precisely the alone listing yous got here, I convey shared a lot of interview questions on subject wise e.g. yous tin dismiss honor often asked questions from Thread, Collections, Strings as well as other of import Java classes. Apart from coding questions, these fact based Java programming linguistic communication questions are really of import to exercise good on whatever interview. It's fifty-fifty to a greater extent than of import for freshers as well as less experienced developer because they are usually asked these questions to a greater extent than often than experienced developers. By the way, yous are most welcome to contribute inward this list.

How To Convert Map To Listing Inwards Coffee Amongst Example

Before converting a Map to a List inwards Java,  we should hold upwards really clear most these information structures which are widely  used inwards Java. So let's get amongst Map. What is Map? Map is an Interface inwards Java which shop key as well as value object. It's Java representation of pop hash tabular array information construction which allows y'all to search an existing chemical ingredient inwards O(1) time, at the same fourth dimension equally good makes insertion as well as removal easier.  We utilization a key object to cry back the value object past times using hashing functionality provided past times Map. As nosotros possess got seen inwards how acquire method of HashMap works, In Java, equals() as well as hashcode() method are an integral portion of storing as well as retrieving object from it. The map allows duplicate values exactly no duplicate keys. Map has its implementation inwards diverse classes similar HashMap, ConcurrentHashMap, as well as TreeMap. The Map interface equally good provides iii collection views, which allow a map's contents to hold upwards viewed equally a develop of keys, collection of values, or develop of key-value mappings.


Now let's sympathise what is a List inwards Java, It is equally good an interface to render an ordered collection based on index. Elements tin hold upwards inserted as well as deleted using positions as well as duplicate elements are allowed inwards the list.

There are multiple implementation of List is available inwards Java e.g. ArrayList, which is based inwards array as well as LinkedList which is based inwards linked listing information structure. Now let's encounter a Java plan which is used to convert a Map to List.




Map to List inwards Java

Here is our sample plan to convert a Map to List inwards Java. This event is divided into iii parts; In showtime portion nosotros possess got converted keys of HashMap into List. Map allows y'all to acquire a sentiment of all keys of Map equally Set because duplicate keys are non permitted. If y'all know how to convert Set to List, y'all tin easily convert this Set of keys into List of keys.

In sec example, nosotros possess got converted all values of Map into List. Map provides a Collection sentiment of all values, because values tin hold upwards duplicates. By using re-create constructor of Collection itself y'all tin easily convert this Collection of Map values into List. In tertiary example, nosotros volition encounter how to convert all entries of HashMap into List. Just similar keys, Map equally good provides a Set sentiment of all entries. Similar to before example, nosotros tin equally good shop all entries into List.

You tin equally good read Core Java Volume i - Fundamentals past times Cay S. Horstmann to larn to a greater extent than most dissimilar collection classes inwards Java.

 Before converting a Map to a List inwards Java How To Convert Map to List inwards Java amongst Example



Java Program to convert a Map to a List 


import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Set;  /**  * Java Program to Convert HashMap into ArrayList inwards Java  */ public class MapToList {      public static void main(String... args) {                  HashMap<String, Integer> schoolAgeCriteria = new HashMap<String, Integer>();          // preparing HashMap amongst keys as well as values         schoolAgeCriteria.put("NursuryClass historic current criteria", 3);         schoolAgeCriteria.put("KinderGarden1 historic current criteria ", 4);         schoolAgeCriteria.put("KinderGarden2 historic current criteria ", 5);         schoolAgeCriteria.put("PrimarySchool historic current criteria", 6);         System.out.println("Size of  schoolAgeCriteria Map: " + schoolAgeCriteria.size());                   // 1st Example : Converting HashMap keys into ArrayList         Set<String> keySet = schoolAgeCriteria.keySet();         List<String> schoolKeyList = new ArrayList<String>(keySet);                  System.out.println("Size of Key listing from Map: " + schoolKeyList.size());          // impress listing element         System.out.println("Printing HashMap keys from converted listing : ");         for (String key : schoolKeyList) {             System.out.println(key);         }                   // sec Example : Converting HashMap Values into ArrayList         Collection<Integer> values = schoolAgeCriteria.values();         List<Integer> schoolValueList = new ArrayList<Integer>(values);                  System.out.println("Size of Value listing from Map: " + schoolValueList.size());          // impress values from list         System.out.println("Printing HashMap values from converted listing :");         for (Integer value : schoolValueList) {             System.out.println(value);         }                            // tertiary Example : Converting HashMap into ArrayList using Entry Set         Set<Entry<String, Integer>> develop = schoolAgeCriteria.entrySet();         List<Entry<String, Integer>> schoolAgeCriteriaList = new ArrayList<>(set);         Iterator<Entry<String, Integer>> it = schoolAgeCriteriaList.iterator();                  while (it.hasNext()) {             Entry<String, Integer> entry = it.next();             System.out.println("Entry from converted listing : " + entry);         }      } }  Output Size of  schoolAgeCriteria Map: 4 Size of Key listing from Map: 4 Printing HashMap keys from converted listing :  PrimarySchool historic current criteria KinderGarden1 historic current criteria  KinderGarden2 historic current criteria  NursuryClass historic current criteria Size of Value listing from Map: 4 Printing HashMap values from converted listing : 6 4 5 3 Entry from converted listing : PrimarySchool historic current criteria=6 Entry from converted listing : KinderGarden1 historic current criteria =4 Entry from converted listing : KinderGarden2 historic current criteria =5 Entry from converted listing : NursuryClass historic current criteria=3

You tin encounter that how mappings from a Map is converted into a List which is printed inwards the console.

Here is equally good a hierarchical diagram of Java Collection framework, y'all tin encounter Map is non a subclass or subinterface of Collection, they are from the sepearte hierarchy.

 Before converting a Map to a List inwards Java How To Convert Map to List inwards Java amongst Example


That'a all most how to convert Map to List inwards Java. There are many province of affairs when y'all require this e.g. passing Map's content into a legacy or library method which bring List. You tin utilization this event  to convert a hash map to listing using its key value ,by using key nosotros brand ArrayList of keys equally good ArrayList of values . If y'all similar to know to a greater extent than most information construction provided past times Java inwards Collection framework, encounter top five information structures from Java API.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures as well as Algorithms: Deep Dive Using Java
Algorithms as well as Data Structures - Part i as well as two
Data Structures inwards Java nine past times Heinz Kabutz


Sunday, November 24, 2019

Top X Tricky Coffee Interview Questions Too Answers

What is a tricky question? Well, tricky Java interview questions are those questions which direct maintain some surprise chemical component on it. If yous endeavour to reply a tricky enquiry amongst mutual sense, yous volition most probable neglect because they require some specific knowledge. Most of the tricky Java questions comes from confusing concepts similar component subdivision overloading as well as overriding, Multi-threading which is truly tricky to master, grapheme encoding, checked vs unchecked exceptions as well as subtle Java programming details similar Integer overflow. Most of import thing to reply a tricky Java enquiry is mental attitude as well as analytical thinking, which helps fifty-fifty if yous don't know the answer. Anyway inward this Java article nosotros volition run across 10 Java questions which are existent tricky as well as requires to a greater extent than than average cognition of Java programming linguistic communication to reply them correctly. As per my experience, in that location is e'er ane or 2 tricky or tough Java interview question on whatever meat Java or J2EE interviews, therefore it's proficient to fix tricky questions from Java inward advance.

If I direct maintain an interview, I purposefully position this variety of enquiry to approximate the depth of candidate's agreement inward Java. Another wages of bespeak such enquiry is the surprising element, which is a key cistron to position the candidate on some pressure level during interviews.

Since these questions are less common, in that location is proficient adventure that many Java developer doesn't know virtually it.  You won't detect these questions fifty-fifty on pop Java interview books similar Java Programming Interview exposed, which is all the same an splendid guide for Java interviews.

Btw, if yous don't detect these enquiry tricky enough, therefore yous should depository fiscal establishment check Joshua Bloch's some other classic book, Java Puzzlers for super tricky questions. I am sure yous volition detect them challenging enough.




10 Tricky Java interview enquiry - Answered

Here is my listing of 10 tricky Java interview questions, Though I direct maintain prepared as well as shared lot of hard meat Java interview enquiry as well as answers, But I direct maintain chosen them every bit Top 10 tricky questions because yous tin non guess answers of this tricky Java questions easily, yous demand some subtle details of Java programming linguistic communication to reply these questions.

Question: What does the next Java plan print?
public class Test {     public static void main(String[] args) {         System.out.println(Math.min(Double.MIN_VALUE, 0.0d));     } }
Answer: This enquiry is tricky because dissimilar the Integer, where MIN_VALUE is negative, both the MAX_VALUE as well as MIN_VALUE of the Double course of report are positive numbers. The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the to the lowest degree amid all double values. So dissimilar the obvious answer, this plan volition impress 0.0 because Double.MIN_VALUE is greater than 0. I direct maintain asked this enquiry to Java developer having sense upwards to 3 to v years as well as surprisingly almost 70% candidate got it wrong.


What volition give off if yous position render declaration or System.exit () on endeavour or grab block? Will finally block execute?
This is a really pop tricky Java enquiry as well as it's tricky because many programmers think that no thing what, but the finally block volition e'er execute. This enquiry challenge that concept past times putting a render declaration inward the endeavour or grab block or calling System.exit() from endeavour or grab block. Answer of this tricky enquiry inward Java is that finally block volition execute fifty-fifty if yous position a render declaration inward the endeavour block or grab block but finally block won't run if yous telephone band System.exit() from endeavour or grab block.


Question: Can yous override a mortal or static method inward Java?
Another pop Java tricky question, As I said method overriding is a proficient theme to inquire play tricks questions inward Java. Anyway, you tin non override a mortal or static method inward Java, if yous create a similar method amongst same render type as well as same method arguments inward fry course of report therefore it volition enshroud the superclass method, this is known every bit method hiding.

Similarly, yous cannot override a mortal method inward sub course of report because it's non accessible there, what yous do is create some other mortal method amongst the same advert inward the fry class. See Can yous override a mortal method inward Java or to a greater extent than details.



Question: What do the facial expression 1.0 / 0.0 volition return? volition it throw Exception? whatever compile fourth dimension error?
Answer: This is some other tricky enquiry from Double class. Though Java developer knows virtually the double primitive type as well as Double class, acre doing floating indicate arithmetics they don't pay plenty attending to Double.INFINITY, NaN, as well as -0.0 as well as other rules that principle the arithmetics calculations involving them. The elementary reply to this enquiry is that it volition non throw ArithmeticExcpetion as well as render Double.INFINITY.

Also, Federal Reserve annotation that the comparing x == Double.NaN e'er evaluates to false, fifty-fifty if x itself is a NaN. To attempt if x is a NaN, ane should occupation the method telephone band Double.isNaN(x) to depository fiscal establishment check if given number is NaN or not. If yous know SQL, this is really around NULL there.

Btw, If yous are running out of fourth dimension for your interview preparation, yous tin likewise depository fiscal establishment check out Java Programming Interviews exposed for to a greater extent than of such pop questions,


 tricky Java interview questions are those questions which direct maintain some surprise chemical component on i Top 10 Tricky Java interview questions as well as Answers



Does Java back upwards multiple inheritances?
This is the trickiest enquiry inward Java if C++ tin back upwards instantly multiple inheritances than why non Java is the declaration Interviewer often give. Answer of this enquiry is much to a greater extent than subtle therefore it looks like, because Java does back upwards multiple inheritances of Type past times allowing an interface to extend other interfaces, what Java doesn't back upwards is multiple inheritances of implementation. This distinction likewise gets blur because of default method of Java 8, which at nowadays provides Java, multiple inheritances of demeanor every bit well. See why multiple inheritances are non supported inward Java to reply this tricky Java question.



What volition give off if nosotros position a key object inward a HashMap which is already there?
This tricky Java enquiry is component subdivision of some other oft asked question, How HashMap industrial plant inward Java. HashMap is likewise a pop theme to create confusing as well as tricky enquiry inward Java. Answer of this enquiry is if yous position the same key ane time again therefore it volition supersede the former mapping because HashMap doesn't allow duplicate keys. The Same key volition lawsuit inward the same hashcode as well as volition halt upwards at the same seat inward the bucket.

 Each bucket contains a linked listing of Map.Entry object, which contains both Key as well as Value. Now Java volition direct maintain the Key object from each entry as well as compare amongst this novel key using equals() method, if that render truthful therefore value object inward that entry volition live replaced past times novel value. See How HashMap industrial plant inward Java for to a greater extent than tricky Java questions from HashMap.



Question: What does the next Java plan print?
public class Test {     public static void main(String[] args) throws Exception {         char[] chars = new char[] {'\u0097'};         String str = new String(chars);         byte[] bytes = str.getBytes();         System.out.println(Arrays.toString(bytes));     } }

Answer: The trickiness of this enquiry lies on grapheme encoding as well as how String to byte array conversion works. In this program, nosotros are get-go creating a String from a grapheme array, which only has ane grapheme '\u0097', afterward that nosotros are getting the byte array from that String as well as printing that byte. Since \u0097 is within the 8-bit attain of byte primitive type, it is reasonable to guess that the str.getBytes() telephone band volition render a byte array that contains ane chemical component amongst a value of -105 ((byte) 0x97).

However, that's non what the plan prints as well as that's why this enquiry is tricky. As a thing of fact, the output of the plan is operating arrangement as well as locale dependent. On a Windows XP amongst the the U.S. locale, the higher upwards plan prints [63], if yous run this plan on Linux or Solaris, yous volition acquire different values.

To reply this enquiry correctly, yous demand to know virtually how Unicode characters are represented inward Java char values as well as inward Java strings, as well as what role grapheme encoding plays inward String.getBytes().

In elementary word, to convert a string to a byte array, Java iterate through all the characters that the string represents as well as plough each ane into a number of bytes as well as finally position the bytes together. The dominion that maps each Unicode grapheme into a byte array is called a grapheme encoding. So It's possible that if same grapheme encoding is non used during both encoding as well as decoding therefore retrieved value may non live correct. When nosotros call str.getBytes() without specifying a grapheme encoding scheme, the JVM uses the default grapheme encoding of the platform to do the job.

The default encoding system is operating arrangement as well as locale dependent. On Linux, it is UTF-8 as well as on Windows amongst a the U.S. locale, the default encoding is Cp1252. This explains the output nosotros acquire from running this plan on Windows machines amongst a the U.S. locale. No thing which grapheme encoding system is used, Java volition e'er interpret Unicode characters non recognized past times the encoding to 63, which represents the grapheme U+003F (the enquiry mark, ?) inward all encodings.



If a method throws NullPointerException inward the superclass, tin nosotros override it amongst a method which throws RuntimeException?
One to a greater extent than tricky Java questions from the overloading as well as overriding concept. The reply is yous tin really good throw superclass of RuntimeException inward overridden method, but yous tin non do same if its checked Exception. See Rules of method overriding inward Java for to a greater extent than details.



What is the number amongst next implementation of compareTo() method inward Java
public int compareTo(Object o){    Employee emp = (Employee) o;    return this.id - e.id; }
where an id is an integer number.
Well, 3 is zilch wrong inward this Java enquiry until yous guarantee that id is e'er positive. This Java enquiry becomes tricky when yous can't guarantee that id is positive or negative. the tricky component subdivision is, If id becomes negative than subtraction may overflow as well as create an wrong result. See How to override compareTo method inward Java for the consummate reply of this Java tricky enquiry for an experienced programmer.



How do yous ensure that due north thread tin access due north resources without deadlock?
If yous are non good versed inward writing multi-threading code therefore this is a existent tricky enquiry for you. This Java enquiry tin live tricky fifty-fifty for the experienced as well as senior programmer, who are non truly exposed to deadlock as well as race conditions. The key indicate hither is ordering, if yous acquire resources inward a exceptional lodge as well as liberate resources inward the contrary lodge yous tin forestall deadlock. See how to avoid deadlock inward Java for a sample code example.



Question: Consider the next Java code snippet, which is initializing 2 variables as well as both are non volatile, and 2 threads T1 as well as T2 are modifying these values every bit following, both are non synchronized
int x = 0; boolean bExit = false;  Thread 1 (not synchronized) x = 1;  bExit = true;  Thread 2 (not synchronized) if (bExit == true)  System.out.println("x=" + x);
Now tell us, is it possible for Thread 2 to impress “x=0”?

Answer: It's impossible for a listing of tricky Java questions to non incorporate anything from multi-threading. This is the simplest ane I tin get. Answer of this enquiry is Yes, It's possible that thread T2 may impress x=0.Why? because without whatever didactics to compiler e.g. synchronized or volatile, bExit=true might come upwards earlier x=1 inward compiler reordering. Also, x=1 powerfulness non transcend away visible inward Thread 2, therefore Thread 2 volition charge x=0. Now, how do yous ready it?

 When I asked this enquiry to a pair of programmers they reply differently, ane suggests to brand both threads synchronized on a mutual mutex, some other ane said brand both variable volatile. Both are correct, every bit it volition forestall reordering as well as guarantee visibility.

But the best reply is yous only demand to make bExit as volatile, therefore Thread 2 tin entirely impress “x=1”. x does non demand to live volatile because x cannot live reordered to come upwards after bExit=true when bExit is volatile.



What is deviation betwixt CyclicBarrier as well as CountDownLatch inward Java
Relatively newer Java tricky question, entirely been introduced from Java 5. The master copy deviation betwixt both of them is that yous tin reuse CyclicBarrier fifty-fifty if Barrier is broken, but yous tin non reuse CountDownLatch inward Java. See CyclicBarrier vs CountDownLatch inward Java for to a greater extent than differences.


What is the deviation betwixt StringBuffer as well as StringBuilder inward Java?
Classic Java questions which some people think tricky as well as some reckon really easy. StringBuilder inward Java was introduced inward JDK 1.5 as well as the entirely deviation betwixt both of them is that StringBuffer methods e.g. length(), capacity() or append() are synchronized acre corresponding methods inward StringBuilder are non synchronized.

Because of this primal difference, concatenation of String using StringBuilder is faster than StringBuffer. Actually, it's considered the bad practise to occupation StringBuffer anymore, because, inward almost 99% scenario, yous perform string concatenation on the same thread. See StringBuilder vs StringBuffer for to a greater extent than differences.



Can yous access a non-static variable inward the static context?
Another tricky Java enquiry from Java fundamentals. No, yous tin non access a non-static variable from the static context inward Java. If yous try, it volition give compile fourth dimension error. This is truly a mutual job beginner inward Java human face upwards when they endeavour to access instance variable within the master copy method. Because master copy is static inward Java, as well as instance variables are non-static, yous tin non access instance variable within main. See, why yous tin non access a non-static variable from static method to larn to a greater extent than virtually this tricky Java questions.


How many String objects are created past times the next code?
 tricky Java interview questions are those questions which direct maintain some surprise chemical component on i Top 10 Tricky Java interview questions as well as Answers


Now, it's practise time, hither are some questions for yous guys to answer, these are contributed past times readers of this blog, big thank yous to them.
  1. When doesn't Singleton rest Singleton inward Java?
  2. is it possible to charge a course of report past times 2 ClassLoader?
  3. is it possible for equals() to render false, fifty-fifty if contents of 2 Objects are same?
  4. Why compareTo() should live consistent to equals() method inward Java?
  5. When do Double as well as BigDecimal give different answers for equals() as well as compareTo() == 0. 
  6. How does "has before" apply to volatile work?
  7. Why is 0.1 * 3 != 0.3,
  8. Why is (Integer) 1 == (Integer) 1 but (Integer) 222 != (Integer) 222 as well as which ascendence arguments alter this.
  9. What happens when an exception is thrown past times a Thread?
  10. Difference betwixt notify() as well as notifyAll() call?
  11. Difference betwixt System.exit() as well as System.halt() method?
  12. Does next code legal inward Java? is it an instance of method overloading or overriding?
  13. public String getDescription(Object obj){    return obj.toString; } public String getDescription(String obj){    return obj; } as well as public void getDescription(String obj){    return obj; }


This was my listing of Some of the most mutual tricky questions inward Java. It's non a bad thought to fix tricky Java enquiry earlier appearing for whatever meat Java or J2EE interview. One or 2 open-ended or tricky enquiry is quite mutual inward Java interviews.


Further Reading
If yous are looking for super challenging play tricks coding questions therefore yous should depository fiscal establishment check out Joshua Bloch some other classic book, the Java Puzzlers, I am sure yous sick detect them truly challenging to solve, I sure as shooting did.

 tricky Java interview questions are those questions which direct maintain some surprise chemical component on i Top 10 Tricky Java interview questions as well as Answers



Hungry for to a greater extent than Java Interview Question as well as Answer post, depository fiscal establishment check out these articles

Saturday, November 23, 2019

Difference Betwixt Hashmap Vs Identityhashmap Inwards Java?

The IdentityHashMap is 1 of the lesser known Map implementation from JDK. Unlike full general purposes Map implementations similar HashMap in addition to LinkedHashMap, it is rattling especial in addition to it's internal working is quite dissimilar than HashMap. The primary deviation betwixt IdentityHashMap in addition to HashMap inwards Java is that old uses equality operator (==) instead of equals() method to compare keys. Which way yous postulate the same key object to think the value from IdentityHashMap, yous cannot think values past times using about other key which is logically equal to previous key. Another of import deviation betwixt HashMap in addition to IdentityHashMap is that IdentityHashMap doesn't job hashCode() method instead it uses System.identityHashCode() method. This is a pregnant deviation because right away yous tin compass the axe job mutable objects every bit key inwards Map whose hash code are probable to alter when the mapping is stored within IdentityHashMap.

Other Map implementation which uses equals() in addition to hashCode() doesn't move good amongst mutable keys. For example, if yous shop a mapping inwards HashMap in addition to and thence went on to alter the key object the hashCode generated past times key afterward volition non move the same every bit before. Even if yous provide same, the equals() method volition non provide truthful when yous compare key object from entry to given key object.

So, that's the basic deviation betwixt IdentityHashMap in addition to a HashMap inwards Java, let's encounter a twosome of to a greater extent than in addition to about code to empathise this concept better.



IdentityHashMap vs HashMap inwards Java

As I said, IdentityHashMap is a lesser known cast from JDK, yous mightiness never job this cast inwards your projection precisely a practiced run a endangerment is that somebody else mightiness convey already used. Since most of the programmers pass to a greater extent than fourth dimension reading code than writing, it's of import to know what  is IdentityHashMap inwards Java, what it does, how it works, in addition to when to job this cast inwards your Java application.

Once yous empathise the difference betwixt IdentityHashMap in addition to HashMap, yous volition automatically larn how to brand the best job of this class.

1) The kickoff in addition to firstly deviation is that IdentityHashMap internally uses == operator instead of equals() method, which way yous tin compass the axe shop a String object into IdentityHashMap in addition to afterward telephone telephone the contains() method to banking concern friction match if it exists inwards the Map, it volition entirely provide truthful if both objects is same inwards heap space. It volition provide faux fifty-fifty if both objects has same content, every bit shown below:

import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map;  public class HashMapVsIdentityHashMap {    public static void main(String[] args) {      Map<String, Integer> idMap = new IdentityHashMap<>();     Map<String, Integer> hashMap = new HashMap<>();      String str = new String("Java");      idMap.put(str, 1);     hashMap.put(str, 1);      boolean isExist = idMap.containsKey("Java"); // false     boolean isPresent = hashMap.containsKey("Java"); // true      System.out.println("Does Java exists inwards IdentityHashmap? : " + isExist);     System.out.println("Does Java exists inwards Hashmap? : " + isPresent);    }  }  Output: Does Java be in IdentityHashmap? : false Does Java be in Hashmap? : true


You postulate JDK seven to run this programme because nosotros convey used diamond operator (<>) to shorten the Generic code, though nil stops yous from existence running it on Java SE vi in 1 lawsuit yous take the diamond operator in addition to specify the types on correct side of initialization every bit good e.g.

instead of
Map<String, Integer> idMap = new IdentityHashMap<>();
job this
Map<String, Integer> idMap = new IdentityHashMap<String, Integer>();

Using Generic is too 1 of the Java coding best practices which yous should e'er follow ship Java 5. You tin compass the axe see Java Coding Guidelines: 75 Recommendations for Reliable in addition to Secure Programs for to a greater extent than of such best practices.

 Unlike full general purposes Map implementations similar  Difference betwixt HashMap vs IdentityHashMap inwards Java?



2) Another pregnant deviation betwixt HashMap in addition to IdentityHashMap is that afterward uses System.identityHashCode() instead of hashCode() method of key object. This way yous tin compass the axe too job a mutable object every bit a key inwards IdentityHashMap, which is non supported past times HashMap inwards Java. I hateful at that spot won't move whatever compilation mistake precisely it volition non move every bit expected i.e. yous volition non move able to think object dorsum in 1 lawsuit yous modified it solid set down because its hashCode too got changed. Let's encounter how this move inwards IdentityHashMap amongst an example.

Let's assume nosotros convey a cast called CreditCard, which has a plain called expiry, which is nil precisely a formatted appointment inwards String format. Later nosotros alter the CreditCard object past times changing it's choke in addition to encounter if yous tin compass the axe discovery it out over again from both IdentityHashMap in addition to HashMap or not.

Java Program to exhibit deviation betwixt HashMap vs IdentityHashMap
import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map;  public class sds {    public static void main(String[] args) {      CreditCard visa = new CreditCard("VISA", "04/12/2019");     CreditCard original = new CreditCard("Master", "04/11/2020");     CreditCard amex = new CreditCard("American Express", "04/10/2021");          Map<CreditCard, String> cardToExpiry = new HashMap<>();     Map<CreditCard, String> cardToExpiryIdenity = new IdentityHashMap<>();          // inserting objects to HashMap     cardToExpiry.put(visa, visa.getExpiryDate());     cardToExpiry.put(master, master.getExpiryDate());     cardToExpiry.put(amex, amex.getExpiryDate());          // inserting objects to IdentityHashMap     cardToExpiryIdenity.put(visa, visa.getExpiryDate());     cardToExpiryIdenity.put(master, master.getExpiryDate());     cardToExpiryIdenity.put(amex, amex.getExpiryDate());               System.out.println("before modifying keys");     String result = cardToExpiry.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA bill of fare exists inwards HashMap? " + result);          result = cardToExpiryIdenity.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA bill of fare exists inwards IdenityHashMap? " + result);          // modifying value object     visa.setExpiryDate("02/11/2030");          System.out.println("after modifying keys");     result = cardToExpiry.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA bill of fare exists inwards HashMap? " + result);          result = cardToExpiryIdenity.get(visa) != null? "Yes" : "No";     System.out.println("Does VISA bill of fare exists inwards IdenityHashMap? " + result);   }   }  class CreditCard{   private String issuer;   private String expiryDate;         public CreditCard(String issuer, String expiryDate) {     this.issuer = issuer;     this.expiryDate = expiryDate;   }     public String getIssuer() {     return issuer;   }     public String getExpiryDate() {     return expiryDate;   }      public void setExpiryDate(String expiry){     this.expiryDate = expiry;   }     @Override   public int hashCode() {     concluding int prime number = 31;     int result = 1;     result = prime number * result         + ((expiryDate == null) ? 0 : expiryDate.hashCode());     result = prime number * result + ((issuer == null) ? 0 : issuer.hashCode());     return result;   }     @Override   public boolean equals(Object obj) {     if (this == obj)       return true;     if (obj == null)       return false;     if (getClass() != obj.getClass())       return false;     CreditCard other = (CreditCard) obj;     if (expiryDate == null) {       if (other.expiryDate != null)         return false;     } else if (!expiryDate.equals(other.expiryDate))       return false;     if (issuer == null) {       if (other.issuer != null)         return false;     } else if (!issuer.equals(other.issuer))       return false;     return true;   }       }  Output earlier modifying keys Does VISA bill of fare exists in HashMap? Yes Does VISA bill of fare exists in IdenityHashMap? Yes after modifying keys Does VISA bill of fare exists in HashMap? No Does VISA bill of fare exists in IdenityHashMap? Yes


From the output yous tin compass the axe encounter that in 1 lawsuit yous changed the CreditCard object, which is key inwards both HashMap in addition to IdentityHashMap, yous are non able to think object inwards instance of HashMap precisely yous able to think when yous job IdentityHashMap because old uses equals() method which provide dissimilar value in 1 lawsuit choke appointment changed in addition to afterward uses == operator which provide truthful because inwards both cases the object is the same inwards heap.

You tin compass the axe too read Core Java Volume 1 - Fundamentals past times Cay S. Horstmann to larn to a greater extent than nearly IdentityHashMap cast inwards Java.

Here are about to a greater extent than of import points nearly IdenityHashMap inwards Java:
  1. It uses identity methods i.e. equals in addition to hashCode to think values.
  2. It uses reference equality instead of equals() method i.e. object1 == object2 instead of object1.equals(object2).
  3. For hashing, it uses System.identityHashCode(key) instead of key.hashCode() every bit used past times other Map implementations.
  4. The java.util.IdenityHashMap cast is used inwards Serialization in addition to deep copying, where your key is "Class" object or interned String. 

 Unlike full general purposes Map implementations similar  Difference betwixt HashMap vs IdentityHashMap inwards Java?


That's all nearly the difference betwixt IdentityHashMap in addition to HashMap inwards Java. There are rare cases where yous desire to job the IdentifyHashMap precisely it's practiced to know nearly it.


Related Java HashMap tutorials  you may like
  • How does get() method of HashMap move inwards Java? (answer)
  • What is the difference betwixt HashMap in addition to Hashtable inwards Java? (answer)
  • What is the difference betwixt ArrayList in addition to HashMap inwards Java? (answer)
  • What is the deviation betwixt HashSet in addition to HashMap inwards Java? (answer)
  • Difference betwixt ConcurrentHashMap in addition to HashMap inwards Java? (answer)
  • How HashSet internally plant inwards Java? (answer)
  • How ConcurrentHashMap internally plant inwards Java? (answer)

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures in addition to Algorithms: Deep Dive Using Java