Core Java Interview Questions & Answers | Top FAQs Explained! | @Javatechie

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone welcome to Java Tei are you ready to master in core Java and is your next interview if yes you have come to the right place in today's video we have compiled a series of challenging core Java interview questions and comprehensive answers that will help you serpen your skills and boost your confidence we'll cover the fundamental concepts Advanced topics and practical example that will give you the confidence to tackle any Java interview okay all right so without any further delay let's get [Music] started even though your pressure or experience it does not matter if you show Java in your profile the first question from interviewer what is the pillar of oops concept so you should be very strong in this oops concept which is nothing objectoriented programming language and this is one key component in Java so pillar of oops concept encapsulation inheritance polymorphism and obstruction encapsulation means binding all field as a single entry so you need to follow certain rules to achieve this encapsulation you need to Define all the attribute as private and you need to use all public exposed method which is getter and Setter method and usually inheritance we use to reuse all the property of parent in our child you can go with class and interface in the same type if it is a class class or interface interface you can go with extends if the type is different you can go with implements the next polymorphism poly means single with multiple implementation okay which is nothing our overloading and overriding so if you know what is overloading and overriding you'll able to answer about this polymorphism okay and the next is obstruction obstruction means hiding the implementation to the end user give them only the functionality so I'll show you in the code what exactly this encapsulation inheritance polymorphism and obstruction now the next question you'll get where did you use this concept in your project so to answer this question already I created one small PC so that I can show you all the implementation of oops okay usually we do use encapsulation in real time in one of our entity or dto class so if you'll go to this entity package this is what inventory service I just created couple of class to show you about this oops principle now if I'll go inside this entity class I have the all the field which is private and I have only getter and Setter method now whoever want to access this item class attributes he need to create the object of it and he need to call this gate method we are not providing the constru Constructor here that's what the encapsulation right and the next is inheritance now usually we follow inheritance in our service or Dow class so if you'll go to the service we have couple of uh op method in our service interface and we have their implementation inventory service IML okay you can see here now this inventory service is parent for me and I have one implementation which is inventory service IML in future if same method want to access by some other class he need to directly create a class and need to implement from this service right that's what the reusability and the next question is polymorphism usually we write polymorphism or we can say we are using overloading and overriding widely if you know what is overloading and overriding the purpose of using overloading having the same method signature with but the argument is different so if You observe here there can be a scenario to add a single item and there can be a scenario to add a list of item so if You observe this is what the method overloading we are using in our project so this is just one of the simple scenario I'm explaining you need to explain to the interviewer based on your project or your code base okay and similarly there is another example of overloading you can see this remove item you can either remove item directly by passing the argument as a object or you can directly remove the item by ID similarly If You observe there is couple of uh another overloading you can search item based on the item name or you can search the item based on the item name and its color or you can search the item based on item name color or price so you can consider these three as a overloaded method okay fine so we understand what is overloading and we understood couple of example or couple of method signature right now where did you use overriding now if you'll go to this interface we have this add item add item now if you'll go to this implementation we just override it means we are just accessing the property of our parent so override always happen in different class if that those class have the inheritance okay so the purpose of using this overriding to reuse the property and in case of over ring all the signature of method should be same so if You observe in parent class go to this service which is our interface if you see this signature add item it have only one argument it have list of argument and and if you check in your implementation class the method signature should be same there is some certain scenario where you can uh find there is multiple way of overriding so let's assume this is one class right if your parent which is your uh inventory service if this is returning some interface then in your implementation class you can return any implementation of it so what I'll do for example let me show you um let me create one domy interface called a okay Java Class A I'm not writing any logic here and I have one class called B now let's assume this B extends for extends from a fine now let's assume in this inventory service the argument is returning the super class which is a and the child class is B okay now if I go to my inventory service IML here inad instead of let's remove this here I can return a object also I can return the B object because B is the subass of a this is one of the tricky scenario you'll find in interview they will try to confuse in case of overriding okay so you need to remember if you returning any parent object as a return type in your interface or class then in your implementation you can return child object of it okay so this is what one of the tricky question so I hope this concept is clear for you apart from that if you'll go to the uh controller I guess yeah if you'll go to the controller we are not injecting the implementation class we are just injecting the interface right that's what the dynamic polymorphism or we can say runtime polymorphism because if You observe I I may have multiple implementation of this inventory service now we have only service IML one I can have IM 2 now we are not injecting the class implementation class rather we are injecting the interface that's what one of the interview question where did you use runtime polymorphism in your project okay now next question explain exception hierarchy in inheritance basically they will try to confuse you this exception hierarchy question with overriding Concept now let me go through one example to clear this doubt let me go to the intelligent now if You observe I have child and parent class now let's go to this parent class If You observe there is a method called M1 and in child we overwrite this method M1 okay now the question here if my parent throws some exception let's say throws exception then is it mandatory that my child need to handle this now if you go to this child there is no compilation error my child is not crying even though parent is throwing the exception now I can add here throw exception or I can ignore it if my parent is throwing it okay now let's try the reverse one let's remove from the parent now if You observe here if my child is throwing the exception then parent must need to handle that he must need to throw it other child will cry Here If You observe add exception to the parent M1 throws okay see here that is what one more interview question so you just need to note it if parent is throwing the exception then it's optional for child to declare the throws but if child is throwing the exception like throws exception then parent must need to throws it okay this is what you need to remember now the next question will be parent child over override scenario so interviewer will try to ask few more question on this override scenario that is also one tricky question we can consider so let's remove this let's assume that I have a parent class and we have method called M1 and if you'll go to the child class we overwrite this method okay now I was creating the object of parent parent new child and I was trying to call the M1 method now maximum people thought that this m one method will call from the parent class okay because if You observe the signature of parent parent equal to new child and people are assuming that this is the object of your parent class now let me run this code you'll see the output then we'll derive more now if you'll see the output we are getting child M1 it means the M1 method is executing from our child class because we override it from the parent we override it in child and here we are not creating the object of parent with the reference of parent we are creating the object of child that's why we are able to access this method from the child class now let's assume I didn't overwrite this method in my child class and if I run it now first it will check in child class because we are creating the object of child first jbm will check this M1 method in child class if it will not found then it will go and check in your parent class now if I run it I'll get the output from parent class I'll not get any compilation error see if You observe your parent M1 if you go to this class and we are printing your parent M1 that's what we are getting If You observe we are not getting any compilation error even though this method is not there in our child class that's what the overriding and or we can say runtime polymorphism okay okay now the next question will be let's go to the slide parent child overrate scenario just to discuss now the next one can we override static and private method answer is no if you'll try to override the static method then that will consider as a method hiding and private method we cannot override because the scope of that private is inside a class it will not visible to the child class now if you'll go to the intellig idid where is the ID yeah this one now let's say I have a static method here B M2 okay now if I'll go to the child and if you try to overwrite this let me add this I'll write at theate override I'm getting the compilation error okay and now if I will call this method with the object of see now I'll try to access this parent new child object and I will call M2 method it will execute from the parent okay now let me run this parent static M1 okay now let me change it to child now if I call the object of child child equal to new child let me do that child I'll get the output from this child class first of all as this is the static method we don't need to create the object of it now from where you want to call this method just use that class name parent. M2 or child. M2 this is how we can call a static method right and it is not overriding at all because this is not part of the instance and now if I declare any method as a private here let me write something private boid test something like that if I'll try to override this method the scope of this particular method inside this parent class I cannot access this test method inside the child because the scope is private even though child extends from parent he should able to access all the class all the attributes or all the members but this private can be visible to the other class okay now if I will try to add that test I'm not getting any option to override it right so that's the reason we cannot override static and private method now next question will be let me go to the slide what is the difference of java 7 and Java it interface so basically in Java 7 we can Define only the abstract method as part of interface but in case of java it you can Define default method and and static method as well as part of java interface now I can show you the purpose of this default method and static method if you go to the intellig ID now let me go to this Java package let's say I have one interface called payment and inside payment I have do transaction method something called add Coupon method and if You observe this this is the default method and in default method you can write the method body okay and if If You observe there is one static method generate transaction report and this is the common feature for all the implementation since this is my payment interface I have the multiple implementation like Google pay PTM and phone pay now the purpose of using this default method to not force to my implementation class to override this method now I have add Coupon method let's say Google pay want to give this add Coupon feature he can override it paytm want to give this ad coupon coupon he can override it but let's assume phone pay don't want to use this add Coupon feature to the user so if you'll go to the phone pay and I I implement it from payment but I didn't overwrite the add Coupon method I'm not getting any compilation error because my method is add Coupon method is default method which will not force to your implementation class to override it before Java 7 before Java it any method present in the interface if you implement from that you must need to overwrite that now since I Define that method as default it is not forcing me to overwrite that's what the purpose of using this default method now so there is few point you can note that ignore if you don't want to add any add Coupon feature in any of your implementation then don't do anything directly access from Super class if you want to use same implementation let's say in this add Coupon I we need to write some logic here but I just added some log statement or sopn statement let's say I just want to give the coupon as a 5 rupees cash back now Google pay also want to give the same feature he can do one thing he can override this method and he can call Super dot add cpon or he can directly uh access it from my interface let's say uh payment dot maybe I need to create the object of it okay while accessing this method inside the main method you need to call let me do it right let me write it okay let's say I created object of payment payment um new Google pay fine I can call payment. add Coupon now I can access the parent property here if I don't want to provide my own implementation then I don't need to override anything I can directly get access from my parent class and if you want to give your own coupon feature let's say uh this phone pay want to give their own coupon feature let's say add Coupon s out he want to give 10% cash back now he can override it okay the purpose of using this default method to not force to the implementation to override that method now static method so if you'll go to this payment this is what the generate transaction report which is common for all the impation if you'll do transaction on Google pay PTM or phone pay at the end we are getting one transaction Report with a unique transaction ID right so if something is common for all the implementation better to keep that as a static in your interface rather than create a separate util class and keep it better to use in the interface itself that's how the purpose of using this default and static method that's how they introduced in Java it so far we complet completed couple of question from oop principle now let's go to the slide now the next question will be what is final finally and finalize this is one of the common question now you can say final is keyword finally is a block which is used for the cleanup activity and finalize is a method which will be called by jvm in periodical manner to clean up the unused object usually when we write system.gc this finalized method is called aut aut atically now to demonstrate that let me go to the intellig now if I'll go to this fundamental let me close this yeah so if You observe here we usually use this finally keyword if you don't want your any attribute to reassign or remodify now let's say since I declare this variable as a final if I will try to reassign it will cry you getting make demo. a as a not final okay so final means you cannot reassign it now usually we write finally block there is multiple combination you can write try with finally or try catch finally usually we need to write this finally for the cleanup activity in real time when we are doing this jdbc connection all result result set stream open we need to use this finally block to clean those stream okay now since we are using the framework hibernate and jpa those clean uh those streams are autoc closable but as for the earlier implementation we must need to clean those streams or we need to close that connection so in that time we usually use the final block because it will always execute right and now the purpose of using this final method If You observe this method is there in object class okay now what I'll do I'll just type object something going wrong yeah let's say object now if you'll go to this object Java you'll find the finalize method which is protected I believe let me type yeah this is the protected finalize method present in object class now once you set your object as a null or if garbage collector will found some object which is not being used and once we call this system.gc it will call this finalize method now what I'll do I'll just run this code If You observe this is what the object of my class I use that object and forcefully I just set it to null to show you that finalize method invocation okay now let me run this code If You observe we are getting finalize method called because one of my object is not used in code because it is null now let me do one thing let me comment this I was doing system.gc or you can call runtime. GC and here my object is not all it's being hold to some reference now if I run this I was not getting that finalize method called statement because finalize method is not called if you'll do the system GC jbm will check any object which is null he didn't find anything so we didn't call this finalized method fine now next question will be let me go to the slide what is equals and hcode Method and its contract this is one of the common question you may need to remember this or you may need to practice this while working with the collection basically the purpose of using this ask code to generate a unique or reference number of an object through which we can easily identify the uniqueness of an object and the purpose of using this equals method to compare to object based on its content okay and it's not guaranteed that if two object having the same has code they may having the same content if has code of two object is same there is no guarantee that equals method of this two object will be same let's take an example to understand this equals and has method and its contract now if I go to my intellig ID now let's go to the project if You observe I created one class called employee and I have two field ID and name and we have default Constructor and parameterized Constructor we have the getter and Setter method and if You observe I wrote this has code manually rather generated it from the ID I wrote it and I was evaluating the H code based on only one field even though we have two field here ID and name and I was just evaluating the hcode based on a single field and I was just writing logic to uh implement the equals method with all or both the field ID and name so once again my employee have two field ID and name I am evaluating the has code based on one field that is ID and I was evaluating the equals based on two field ID and name okay now if You observe employee one I created one not one bant employee E2 new employee I created again the same ID but name is different now if you'll check the H code of these two object you will get same because forcefully I was evaluating the H code based on only one field but if you'll check the content of these two object ID 10111 name is different okay so you'll find this as a false now let me run this code you're getting true hcode is same equal is false okay so usually we need to follow the proper contract of this equals and has code to avoid duplicate in collection let's say I will add the valid equals and hcode Method let me remove this first let's let me not add this equals and has code method what I'll do I just create a collection you know set will not allow duplicate right let me do that employee new employee let me add something the same fine now employees do add employee 1 sorry this should be new haset or some set implementation now let me add employee 2 [Music] add fine now as for the set implementation set will not allow duplicate now if I print this set we should get only one result right because both the object is same has codewise and equals wise and because we are not overriding it first of all so let's run it how this set behave so if I run this we can see two object even though this two object is same still we set is allowing duplicate to us right which is not a correct Behavior it's because we are not following the contract of equals and has code method now what I'll do I'll just overwrite the equals and has code okay next next next now if I run this code we have the equals and has code method if I add those object to the set implementation or map as a key it will not allow the duplicate now now if I run this you can see only one object so it's always recommended to override both equals and hcode Method especially when we are working with any set implementation or hashmap okay we'll discuss more about this equals and hashcode implementation once we start learning has map internal flow in my upcoming video fine next question will be if you'll go to the slide the next question will be what is exception and its hierarchy usually exception we received because of unwanted check or there will be not proper coding to validate the object or some it's kind of programmer mistake right because of some wrong coding we are getting the exception so if you will check the exception hierarchy the super class of exception or error is throwable and if You observe throwable again categorized as a error and exception If You observe the error there will be couple of error which is out of memory error stock overflow error and again if you'll go to the exception it categorized as a two types runtime exception which is unchecked and another is checked exception or usually people says it does compile time exception okay so if you'll check in run time exception null pointer illegal argument arithmetic r index bound of exception these are part of runtime exception this we never know when we'll get this exception because we are not getting any precompilation warning or something like that so these will be considered as runtime exception similarly there is checked exception which is class not found exception IO exception file not found exception SQL exception these are the checked exception usually checked checked exception alternatively called as a compile time exception when you'll say this term compile time exception immediately you'll get the next question why checked exception also called as a compile time exception is it really occurs in compile time answer is no it's just a naming convention people are mentioning that runtime exception and compile time exception never as a developer we found any exception at compil time all the exception will raised at run time only so you need to convince to the interviewer that this compile time exception is not part of compile time so I can give you one example where you can prove yourself that this checked exception or compile time exception will not raise at compile time now if you'll go to the intellig now let me go to the exception folder let's assume I just want to read a file okay so I wrote a class something called Data reader and I have a file on this path now what I'll do I'll just write buffer reader buffer reader buffer reader new file reader of file okay now if You observe at the time of compile we are getting a message or we are getting a warning to handled it okay okay I handled it means better I can write try catch okay I'm going to handle it fine now this is makes sense right we are getting the we are getting the warning at the time of compilation and we are handling it now you can write some logic to read the file Also let's say while be do read line not equal to null there is something wrong okay fine add one more catch then print the content be do read line As for the coding convention this file not found exception or IO exception is checked exception which get one at compile time and we handled it now if I run the code I'll will get the mage message printed in my console there is some data random text we can see in the console but what if I will give some wrong path not intentionally but somehow the path is wrong okay now if I'll run it still we are getting the exception right and we are getting it at run time if You observe the exception type is file not found exception which is checked exception and we are getting at wrun time so it means there will be no exception which will be raised in compile time so we cannot say checked exception as a compile time exception okay so this way you need to convince to your interviewer that this is not a compile time exception hope this concept is clear for you now the next question how to write your own custom exception usually we need to write our custom exception always we are not going to use the checked exception or unchecked exception as part of our project now how you can write your custom exception now if you'll go to the intellig I can write a custom exception right away so what I'll do I let's say I'll create a class let's say order not found exception Okay order not found exception so to create a custom exception first you need to extend your class either from exception or from run time it's up to you what you want to implement so if you'll extend it from run time exception then your custom exception will be behave as a runtime exception if you'll extend it from exception it will behave as a checked exception okay so based on your requirement you can go ahead and Implement either or extend either exception or rtime exception now the next step you need to define a Constructor of this order not found exception class so what I'll do I'll just write a Constructor public order not found exception I'll give some message because I just want to print some message while throwing the exception then this exception or this message you need to pass to your super class so how you can access you can write super pass the message that's it that is how you can create your custom exception just create a exception class or create a normal class extend it either from exception or runtime exception you know the purpose of both it depends on you or for your project requirement just use one of them then just write the default Constructor and provide the message if you don't want to print any message just ignore it pass the message and pass it to the Super class which is your exception if you go and check in exception you'll find this Constructor right exception string message that's how I passed here now write a test class or something like that Java class test I'll write some method public uh void gate order or something like that I just want to show you how you can throw your custom exception as well okay let's say int order ID usually you need to call the service or Dow here I was just randomly throwing some exception okay let's say if order ID uh what is that int right equal to 101 then throw order not found exception with the message that's how we pass the Constructor here right let's say order not found with ID give the ID order ID fine why this is crying okay through new I need to create the object of that class okay I throw the exception and I throws it I'll tell you what is the purpose of these throw and throws okay else do some logic do some logic now I'll call this class call this method write main method I'll create the object of test test equal to new test test dot get order I'll pass the same intentionally I just want to throw exception okay see now itself I will tell you the purpose of using the thr and thr keyword If You observe forcefully I was throwing the exception and I was defining the throws here now if you define the throws in your method then whoever will be next method caller he must need to handled it so if You observe the main method is calling this gate order method and from gate order method we are defining the throws throw means simply you are delegating the exception to the next method color okay now who is my next method color that is uh main method inside main method I was trying to call this gate order method and it have the signature throws it means you either you need to handle it or else again you just delegate it to the next method color so you can do it in a two way you can define a tri a catch you can now you're handling it okay otherwise pass it to the method signature now who will call to this main method he will get this he he must need to handle again okay because you are defining the thr means you are delegating to the next method caller hey whoever will call My Method please handle this order not found exception or again you just throws it whoever will call you he may need to handle it that is how the hierarchy okay okay and throw means we are simply throwing your exception see usually in service we uh get some Dow access exception you need to wrap it and you need to throw your custom exception that is how the purpose of throw to throw the exception from one layer to another layer but throws to inform to the next method color if you'll call me you'll get one exception either you handled it or you throws it okay so that is the purpose of throw and throws now if I run this this I'll will get the exception exception order not found order not found with ID this this is what the message we passed right so we covered how to create custom exception how to use it also we understood the purpose of throws and throw keyword this is also one of the frequently Asked interview question throws and throw now hope you understand the purpose of these two if do you have any doubt then do let me know in comment section I will clear in a descriptive way okay now next go to the slide and the next question we already discuss what is difference between throw and throws now if you'll go to the next there will be couple of tricky exception programming question uh is something like order of the exception okay I can ask you that question let me go to the intellig and there is a class called exception order now let me Zoom this yeah so if You observe in try I just write system. out. print 10 by 0 which usually give me the arithmetic exception now let me uncomment this I just typed it in intelligence so someone can easily cast there is a compilation error but usually interviewer will ask this question in notepad or some some pen and paper where you will not identify that it will be exception okay so you need to understand the order of it now if You observe I have a try I have a catch I have another catch as for Java we can use multiple catch block right then why my code is crying here because exception is a super class of all the exception arithmetic exception is child of this exception so parent class will never be a first statement in your cat block you just shold it it will work there will be no compilation error fine now there is no error but if you'll keep this exception ex cash statement does first then code will not work because this is what the order exception hierarchy uh usually uh jbm followed okay so parent exception will always be in down it's not will be in first statement that is one of the tricky question now let me change it to the actual question this is how they will ask and they will say whether this code will compile or not if you don't know the order of order of exception hierarchy then you will not able to answer this it leads the compilation error okay fine now next there will be a question for try as finally return return statement couple of scenario they might ask you and the next question will be is final block always executed so let's discuss these two example or these two questions with code so let's try to understand the flow of try Cas finally with return statement go to the intellig ID let me comment this otherwise we cannot compile any code fine now let's go to the project go to the try C finally return flow yeah so if You observe there is a try there is a cat there is a finally and from try I'm returning one catch two finally three now if I call this M1 method I should get the output let me check the let let me show you the output then I will tell you what is the flow you'll get the output as a three because try it goes to the try there is no exception or there is no logical statement who may cause exception so it return one that's fine now since there is no exception in try request will not come to this catch okay and directly it will call the finally since we know finally method will always execute that's the Rion we are getting three now let's assume there is no finally we have only try catch in try there is no exception so request will not goes to my catch so we should get the output as one fine you're getting the output as one now let's assume there is some error let me write something s out 10 0 so this this statement will give some exception now if You observe the output should be two because it request goes to the try and there you will find some exception then it will immediately come to the cash block and there will be a return statement now let's run this you are getting two now if I have finally here s out let's say not not s out return return three I will get output as three because request same flow request will come to the try there is exception it will go to the catch and as you know final will always execute it will print me the three just add it we are getting three fine so there is once you will say finally will always execute then the next question from the interviewer is there any scenario where you can break the rule of finally yeah we can do that the answer should be yes what you can do you can write system do exit pass the number zero or forcefully throw some exception from final itself okay now if I run this code there will be no output because as you know final will always execute once you write the system. exit Z here itself your code is terminated okay just remove this let me see what is the flow you won't get any return return statement at the end of the return we are just terminating it okay so that's how you can change the behavior of finally block to not always execute this is one of the again tricky interview question how you can stop finally to execute okay fine now the next question will be if you'll go to the slide how many way we can create string object there is couple of string object creation scenario interviewer can ask and the next what is SCP or string constant pool area and how it works okay so these three question I'm going to demonstrate in the same example now let me go to my intellig ID let's go to this project and if you'll go there is a I created one class called string object so if you can see this code there is two way we can create string class object so the first one string S1 new string of the literal using new string we can create object of a string and also the second approach string S2 equal to plain string of java which is nothing string literal okay so the answer will be there will there will be two way to create string object using new keyword and another is the string literal now the next question you'll get from the interviewer how many object will be created here in this two statement what is the number of object of a string class now let's understand number of object creation okay so once you write string S1 equal to new string of this Java because of new keyword it will create one object because of new keyword okay and there will be a second object because of this literal okay string S1 equal to new string for new it created one object and which it stored in Hep reference or Hep area okay and because of this Java key reference or literal it will create another object because of literal and it will stored in SCP which is nothing string constant pool area in Java okay so this statement is clear because of this line it created two object one it stored in Hep because of the new keyword and another because of this literal that reference will be stored in SCP which is string constant pool area okay now come to the next statement If You observe here also we are writing a literal string literal string S2 equal to Java now whether it is create object for this or not so initially you can consider it will create one object but this is not the fact it will it will not going to create a object because that is what the purpose of introduced this string constant pool area in Java so if already object exist in this SCP second time whenever you want to use it you can directly get it from SCP string is not going to create another object of it so if You observe this string literal already present in string constant pool area and again you are creating the same literal so that's how it will not create any object so in the first statement and second statement total object count is two okay it's because of string constant pool area so interview interviewer will try to confuse you again how you can prove it that it will create only one object so to get any reference from string constant pool area you can directly use the intern method so what you can do to prove that just print the has code of S1 S1 do has code we are not going to print the S1 do has Cod directly get the object from uh SCP so you can use intern method to get object from SCP which is string constant pool area then compare with the s2. hcode okay see this S1 do intern is nothing this Java key and we are getting the has code of this particular literal and we are trying to compare with the s2. hcode S2 is the same literal we are not string is not going to create a separate object so if you run this you'll get true so let me run this you're getting output as true now to prove that this ENT turn is pointing to SCP what I'll do I I'll just copy this let me add it here now I what I'll do I'll just print this statement what exactly it is giving now if I type S1 inter it should give me Java okay see this so here I'm just trying to convince S1 intern will give me this Java literal which is already existing string constant pool area and second we are trying to create the same literal so S1 do intern. code equal to this S2 both are pointing to the same reference that's how we are getting true Okay so so I will just type it better to note it here inter method used to get reference from SCP okay so I'll add this code base in a GitHub and I will share the link in video description so you can follow the same approach okay fine now the next question will be if you go to the slide why string is imitable first of all you need to understand what this term mean what is imitable exactly imitable means simply you cannot modified it which is unmodifiable or unchangeable now to prove that string is imitable what I can do now go to the intellig ID go to the test imitable string class so if You observe string is equal to Java I created string literal here then I'm trying to concut a another string Java Tey now when I will print this string it will give me the Java even though on the same string we are trying to modify we are trying to add some other character still it is not appending that's what the uh imitable so if I'll run this it should give me the Java only now let's run this we are getting only Java even though we are appending some other string we are not getting that as a output now what happened internally let's say for this literal it created a object in SCP something like one 1 0 it's reference now when you will add s do concard this Tey rather than append this Tey to this Java it created another object let me add that it created some different object with some different number or different uh reference it will not changes in the same object that's what the nature of imitable even though you will modify something it will not reflect okay now you might have question why they make these string classes imitable for time being let's assume string is not imitable okay and you have something called password PWD something like that and someone is going to change something on the password so password is string you added the SC sequence as PWD and in password you are trying to append something some random number or some some value okay now let's say five reference pointing to this password now five object is using this password value they will get PWD now if someone will append something or someone will modify in Middle the all five object who reference to this password will get impacted right so that is a kind of security Bridge isn't it so to make sure there will be no impact to the existing reference who all point to the U main reference that's the reason they make this string class as imitable okay apart from that there is couple of point I just want to highlight let's go to the slide there is couple of key Point string pull is Possible only because string is imitable in Java and as we are using string constant pool area there will be a reusability feature right that's what we learn we created Java two times it created only one time object so this way Java run time saves a lot of Heap space isn't it now the next point you can consider if string is not imitable then it would cause a severe security threat to the application for example database username password are passed as a string to get database connection and in Middle someone changed it now who all ever point to your database they get impacted that's what we understand right now the next point you can consider since string is imitable it is safe for multi-threading since string is imitable you can directly use this instance in multi-threading environment so that if any thread is doing some changes then it won't be visible to another thread means another thread will not get impacted with the existing object and also you can avoid the synchronization okay and the next point you can consider since string is imitable its has code is casted at the time time of creation so when you are creating the string string object that time the has code will be CED so that you can directly use it as a key of your has map so that's why we can say it's a right candidate of the key in a has map it's processing is faster than other has map usually when we add any key in the has map it evaluate the has code since string has code is already CED at the time of creation it will not eval reevaluate again right that's why we can get the faster response now the next question will be how we can use mutable class which is something behave like a string because we know string is immutable right then what all mutable class given in Java which we can use instead of string so there is two uh mutable class we can say string buffer and string Builder now we might have question why there is two class string buffer and string Builder even though both are serving the purpose same which is mutable why there is two class that that you might have question right so to clear that string buffer is synchronized which multiple thread can't parall access it where string buffer is non-synchronized or non-thread shape that can access by multiple thread at same time so you can easily identify the difference here string is imitable which is not thread shape and performance is very high and string buffer and string Builder both are mutable and string buffer is thread sa where string Builder is not thread strip okay and the performance wi string buffer is not good as compared to string Builder so usually we implement this means as for my personal experience we implement this string buffer not string buffer string Builder while generating the dynamic query in our Dow layer so we just keep on appending the uh join statement or query in the string build because at that time we don't need to use the string because every concatenation or every each upen it will create a new object right that's we don't want now to demonstrate the string buffer and string Builder what you can do how we can verify that it is mutable so let's go to the code I'll do the same let's say I have a string buffer or Builder anything you can take as a example SB equal to new string buffer let's say I'll give the same example Java you just add it here Java now I just want to appen something okay so this should be SB and there is a method instead of concer there is a method called append so I append the um some car sequence that is taking just remove it now if I'll print it SB you can directly print the string buffer or else you can type c to two string now let me Zoom this if You observe in string we added Java then we concer TIY and we print s we got the output as Java only because it didn't add it because of the imitability nature now because of this string buffer is mutable we should get the response as Java Tey now just run this we getting Java Tey right now if you'll change it to string Builder okay now if I'll run this it will also beave the same mutable nature you'll get Java as output that is how you can differentiate string string buffer and string Builder with example now once you explain this mutable and immutable nature of string string buffer and string Builder the next question from the interviewer should be how you can write your own custom imitable class we know string is imitable based done the same way can we write our own custom imitable class the answer will be yes you need to do some tricky logic while writing the imitable class so there is few principle which you need to follow to make your class fully imitable so the first step you need to declare your class as final so that no one can extend it okay and the next step declare all instance variable with private and final declare private so that the scope of the variable Within in the class and Define final so that no one can reassign it okay and say no to set methods don't give or don't add Setter method write only getter method so that no one can set or modify the variable they can only get the uh value from the attribute okay and the next step initialize all variable in Constructor this is straightforward right because you are not providing the setter method there is no alternative way to initialize the object that's how Define only the parameterized Constructor then the next step you can initialize variable in Constructor okay so as we are not allowing to write the setter method we need to go with the Constructor approach only and you need to initialize the attributes in Constructor itself now let's assume you have some mutable object in your imitable class then rather than directly return it just return the clone of that object from your getter method there is also few disadvantages of using this clone I'll will show you in the code while writing our own custom imitable class so you need to keep this six point in your mind while writing your own custom imitable class now let's demonstrate how we can do it just go to the intellig ID let me check the class which I created not this one let's go to this this imitable package and I have a class called employee this is this employee class I want to create a custom imitable class means I just want to make this class imitable so that no one can modify any reference of my attribute or no one can modify my variable value okay so the first step I need to declare the class as final I followed that then then the second step uh we need to Define all the attribute as a private final we follow the second step now also we follow the third step we initialized our object inside the Constructor also we follow the fifth step we only Define the getter method okay now can we say this is completely imitable class Let's test it out just go to the main method and I'll create a object of my employee class employee equal to new employee fine so what is that let me check name date of joining so what I'll do I will just create a date object here date date equal to new date fine so I will give the name as something called bant then I'll give the date then I'll will pass list of string right what I'll do I'll write ARS do stream of I'll create new string array I'll just give couple of number let's say 1 2 3 4 5 6 7 8 okay then just convert it to to list fine so we created one employee object now let's verify whether this employee object is imitable or not whether we are able to to modify the value of this employee class or not okay so what I'll do I'll just add it down so that it will be clearly visible yeah so let's verify whether we are able to modify the name or not we are able to modify the date of joining or not you are able to modify the mobile number or not okay now what I'll do I'll just type employee dot date of joining I just want not date of joining the name right the first field equal to something SOS we are not able to modify right it is crying because we Define this variable as a final that's how the first rule we followed and we are unable to modify the name just remove it now name is primitive so we are unable to modify because we declared it as a final now date which is completely mutable class right mutable and it is not a primitive it is a object now let's try to do that what I'll do I will just get the date from employee employee. getet dat of joining dot set some date I'll will set something called some random number okay 10 now if I'll print my employee see now if I print my employe it should not print me this date with the 10 uh 10 right it should print the new date now let's verify run employee. main okay so what I'll do I'll just add some some number five okay better rather than adding it here I can directly pass the new date here new date that's fine just remove it fine so we just get the date object from the employee and we are setting some random number so it should be dat I guess so that we can see the difference right set dat now if I run this let's make it 15 okay if I run this yeah I'm getting 15 which is not a current behavior right imitable means no one can able to modify it but here I'm able to modify the employee object is date object I'm able to modify it right so to avoid this date what we can do rather than return the direct object what you can do you can simply do the Clone just cast it to date now if I run this even though I will change it it will not reflect it is not getting reflected we are getting two only now if I'll make it 20 anything still we'll get the same we are on a able to modify the date object so it's always recommended to go with the Clone or you can create a new date object and pass this date as a reference okay now this is fine we protected two name and date of joining now how you can handle if there is a list of string or list of object so let's verify whether how how it impacted okay so what I'll do I will just add employee. getet mobile do add I will add some number let's say 56 7 8 9 0 1 0 something like that now if I print employee it should give me if it is a imitable it should give me two number because we should not able to modify the existing object or existing variable but here I'm adding something it should not print if it is a real imitable now let's see the output we are getting this 901 0 as well it means we are able to modify the value of our object it means which is not imitable right so in case of string how you can do that simply you can write collections now this one see t o NS Java util do unmodifiable list pass this mobile now if you run this you'll get some exception because you are not allowing anyone to modify okay but that is fact we are not allowing anyone to modify but we don't want to give any exception we simply will not allow that user to modify my mobile even though he will modify it will not reflect that's what our motto right so you can go with collections. on modifiable list or simply what you can do return new RR list copy of the list okay pass the mobile fine now if you run this you should get only these two reference because any modification it will give a new object so it will not happen to the existing list now let me run this yeah so if You observe we are getting this so there is various type of object you need to handle it properly for object you can go with the Clone for list you can create a copy of it and return it rather than return the actual reference okay now these are the straightforward these are primitive and rapper so we did it quickly now what if let's say I have a another class which is mutable let's say I have address class I created this class I have this address class where I have City and Jeep where I have Constructor I have getter and Setter everything I have which is complete complely a mutable class isn't it mutable class and this mutable class I am accessing in my employee immutable class so it will not behave the immutability because this is the mutable class and we need to forcefully make this imitable okay so how we can do that only this particular attribute we want to make it imitable we we cannot uh make imitable this address for our use so what I'll do first rule declare private final then initialized in Constructor refactor ref yeah it is there in Constructor right then Define only the getter method fine now again we are returning the direct object here now let's verify something what I'll do I'll just get the employee. get address first I need to set the address here right so what I'll do I'll create a address object address new address I'll give something what is that city city I will give Bangalore and G I'll give some random number 1012 now I'll set this address to my employee now as for the imitability nature I should not able to modify my address object even though I will modify it should not reflect this or it should not impact to this existing employee object who is using that address now what I'll do I'll just employee. getet address do set City instead of Bangalore I'll set it pun okay now if I run this it should not print the pun because I set using this Bangalore City or Bangalore address in my existing employee so I should not able to modify it to Pune if I can able to modify then there is no concept called imitable okay now let's run this and see the behavior okay so we didn't add the two string here so what I'll do I'll generate the two string here uh alt insert two string now let me run this now if You observe the output city is getting changed to Pune it means still this address is behave as a mutable in my employee mutable class so how we can restrict that simply rather than return the actual address object create a new address object and set all the attribute from the existing address object how you can get it address do get City address dot get chep okay rather than return the actual object I'm just returning one separate copy of it now if I'll run this code I should get Bangalore again yeah I'm getting Bangalore now hence it proved we created our custom imitable class successfully and any modification to my imitable class will not impact to the object which is there my intention is to create this employeers imit class so that at wrong time no one can modify its existing value that's what we achieved it right but there is certain rule you need to follow six principle apart from that do the Clone if it is a object otherwise do the return the new object like this okay so this is one of the common interview question personally I faced many times and they will try to convince they will try to confuse you with this kind of scenario they will try to to add some different object which is completely mutable and they will ask couple of confusion question on time okay fine now the next question will be if you'll go to the slide that is one of the interest question if you will go and check the question which one is good to Store password whether it is string or car array So my answer will be K AR and I am going to highlight why car ARR why not string so this below key points will answer you why you need to go with car array why not string so as we already know string is immutable in Java if you store the password as plain text it will available in memory until the garbage collector clears it right also if you define password something like string password ABC or javat key as a literal it will store in the string constant pool area and which is not easily eligible for garbage collector to destroy it it will always destroy once jvm restarted so which me leads a high security thread isn't it now the next point you can consider since anyone who have access to the memory dump can find the plane password or the text password they can directly get the string and they can misused it so it's always also an overhead it or it's always additional task for a developer to encrypt the password than the pl text okay and next If You observe since string are imitable there are no way contents of string can be changed because of Any change will produce a new string if I let's say I Define the password ABC and in future I just want to make it DF ABCDEF okay if I am going to appen then again it will create a new object new string object which is not a efficient way to use string un necessary it will occupy some memory in your HEAP area so if you will go with the car array in that situation car you can set some limit or you can set the index you can add as many as you want okay and also apart from that it's not safe to print the pl text in a log file or console but if you are using AR it don't print the content of array instead its memory location now let me show you the example let me go back yeah so I have a password string password unknown and I have a car car password which is same unknown now if I print this PL text I can directly see this unknown right but if I directly print the K ARR I can see the memory location of it rather than getting the content of array based on above 4 point I believe it's always recommended to go with the kar rather than string for storing a password fine the next question will be what is marker interface can we create our own marker interface so the my answer will be the marker interface who does not have any method body or any constraints in the interface is called marker interface and also it is called as a tagging interface and the next question can we create our own marker interface yes we can create our own marker interface okay so let's take an example we have the clonable interface serializable interface or remote interface is considered as a marker interface in Java let's take the example of clonable interface if we try to clone an object and that does not implement the interface clonable then jvm throws clone not support exception right let's say I have one employee class and I'm trying to clone the employee object but that employee class didn't Implement clonable interface then jbm will cry that time he will throw clone note support exception hence the Clone hence the clonable marker interface is an indicator to the J BM that we can call the object do clone method if it's implemented clonable that's how it will just inform to the jbm or compiler to add the additional information about the object based on your marker interface okay so the next question can we create our own marker interface let's try that out now let me go to the intellig ID go to the project let's assume I just want to create my own database framework where if a entity is implements my interface then only I want to perform delete create whatever okay now in same scenario how we can do the marker interface I can create my own marker interface so I created one marker interface called deletable If You observe this interface does not have any method body or any constant here right so we can consider this as a marker interface now I have an entity class you can create any entity this is just just for demo purpose I just highlight the class name I have entity class and it extends deletable okay so it need to be interface right interface yeah and I have entity who implements this deletable now we consider this deletable as a marker interface and I will allow those entity who implements from this deletable now I created one da framework class it's just a demo class I write a method called public bir delete and I pass the object here I was checking if object is instance of deletable because this object is nothing my entity right and entity implements from deletable if object instance of deletable then write your own logic otherwise just ignore it okay similar way it's just I added for delete you can add for Save or you can make a common it's just I want to highlight how we can write your custom marker interface so just Define interface wherever you want check whether your class is implements that or instance of that then do your logic this is how jbm identify whether your class implement serializable or clonable or not what all collection you used in your project so to answer to this question you can explain this collection hierarchy to the interviewer you can tell them that you worked on the list interface set interface and map interface also you can tell them the implementation of list that you worked on AR list linked list and as part of set implementation you worked on has set linked has set and Tre set and as part of map implementation you worked on H map linked H map and tree map but before answer this you should know the purpose of each implementation right when to go for list when to go for set and map you need to find out this and based on your project use case you need to provide a valid scenario to the interviewer okay I'm not going in details about the definition of each implement you can find it in Google I just want to highlight few implementation which is widely used in Project also there is few more implementation class like copy and right AR list copy and right RS set and concurrent has map these are also three implementation class introduced as part of java. concurrent package so this concurrent has map copy and WR AR list is widely used I'll will tell you the scenario where exactly you need to use this implementation in coming slide now after explain this hierarchy the next question from the interviewer will be what is the difference between list and set so you can answer list will allow us to store the duplicate object where set will not allow to store duplicate object next you can say list work on index base where set works on based on the has okay and always we need to use list when we want to frequently access the element by using the index where you can say set is used when you want to design a collection of distant element so the moral of using this list and set if you want to allow duplicate object then go for list if you want to maintain a unique object or unique store then you can go for set now next question from the interviewer will be what is the difference between AR list and linked list so if You observe AR list and linked list is the two implementation of list interface now what is the difference between these two so you can tell them AR list internally uses a dynamic array to store the element and linked list internally use a w link list to store the element manipulation with array list is slow because it internally use an array if any element is removed from the array all the bits are shifted in memory so for example let's say I added Five Element to my array list 1 2 3 4 5 and it converted to the array now my array contains 1 2 3 4 5 let's assume I just want to remove third element okay which is three if I remove the third then there will be two more element four and five this four and five need to shift to my previous index where earlier third is there or three was there right so this kind of memory shifted is there in R list where it's not there in link list okay manipulation with link list is faster than R list because it uses a double link list so no bit shifting is required in memory because dou link list already maintain the node reference of previous and next Noe okay now R list is better for storing and accessing data link list is better for manipulating data okay since we talk about the list now the next question from the interviewer can be list object creation scenario here he can show you ARR list ARR list equal to new array list and list list equal to new array list what is the difference between these two and which one is preferable to use a list implementation object so to answer that you can tell them in case of first scenario ARR list ARR list equal to new ARR list here we are directly using the ARR list implementation which is completely a tied coupled right in case of second syntax you can tell them list is a interface with a reference of list or with a reference of parent we are creating the object of its implementation class new ARR list in future if I want to create the linked list object then I simply write new linked list instead of AR list I don't need to change the complete signature that's what we understand as part of runtime polymeris right with the help of parent reference we are creating object of child that is what AR list is a child and list is a interface so to show that what I can do I go to my intelligent I'll go to this test class so if You observe this ARR list is a class right this is a class and it implements from abstract list if You observe it implements from the this list which is nothing a interface if you'll go to this list it is one interface right so here here we are using something like this parent parent equal to new child which is nothing runtime polymeris right fine so you can explain these two syntax to the intervie and also they might ask you why you used string here list of string can't I use any object or can't I remove this they might ask you like this okay but it's always recommended to use the type generic that's what the string type so that my list will allow only the string object so there will be no type cast issue will face in future if you'll maintain the generic okay so let me comment this so this can be also one possible question fine now the next question will be declare a list field with the the final keyword and he will try to ask you some kind of scenario so if you'll go to my intellig I can show you let's say I Define this list as a final okay now let me remove this so here I declar the list as a final now intervie will try to understand after decare it final whether you are able to add object to this list or not okay now I added list add a and b now I just want to print it list okay now if I run it I should see a and b as a response okay even though we declare it is final we can modify it there is no imitability still we can modify but we cannot reassign this list let's say list equal to new array list okay here we are not able to reassign or with the same reference we cannot create another object but final does not does not mean we cannot modify it okay okay so it's kind of this question int I equal to 10 if I declare this int as a final let's say I'm writing here I equal to 11 it is not allowing us right because we are reassigning it so same way if you declare the uh list as a final it does not mean we cannot modify it we can modify it but we cannot reassign it if you don't want to modify it then you can use collections do unmodifiable list okay so this is what one question in final they will try to ask you either in list or set okay fine now the next question will be if you'll go to the slide how can I write custom AR list where I don't want to allow duplicate we know AR list will allow duplicate but I want to create my own AR list where I stop allowing the duplicate how you can write this piece of code this is one of the common interview question so what you can do I'll explain with the the code I created a class called custom aray list what we need to do we just need to extend it from aray list okay then we'll use its own method from the AR list method and we'll override the method and we will provide our own logic so what I'll do I'll just override the add method from the RR list okay what I'll do simply I can write a condition here if this dot contains this object if this object is already there then return true don't add it okay else just add it so I can directly use um return super. add add the object now what I'll do I'll just create couple of object and I want to store in the custom AR list okay so let me create the object of it list one equal to new RR list create the object for this not AR list okay control J remove this generic because we didn't use this generic okay now in this list I will add list one do add let's say I added one okay similarly let me add couple of duplicate now I'll add two now if I print this list sopn then it should not contains any duplicate because we are using our own add method overridden from our list class so let's run it we can see only one and two right even though we added 3 one object it does not allow duplicate so this is how you can create your own custom AR list by extending from R list or any link list and you can provide your own implementation to stop allowing duplicate fine now the next question will be why set does not allow duplicate element we know AR list will allow duplicate element but we can customize and we can maintain a non- duplicate object in Array list by creating our own class but why set does not allow duplicate element so to prove that I will directly show you the source code of Set uh implementation so if I go to the intellig ID now let's say here I'm writing something called set of string something like that set equal to new has set okay now if I'll type set. add set. add method sorry this need to be add I just type set do add add some object here let's say a BC fine now if you'll go inside this add method let's go to the implementation of it let's say haset any any implementation if you'll go if You observe the object which you passed as a add method of set it will add as a key of a map it means add method internally used a map object to store the value where it will consider the past argument as a key and value as a present which is nothing a Dy value okay so if you'll go here present is a dmy object it means set implementation internally used a map to store a object as a key so we know map key will not allow duplicate right the reason I will tell you in next slide with animation so for time being you just remember that set method internally used map and the object which will pass as a add method argument in set it will pass as a key of a map okay if you know the map internal flow then you can answer at the same time okay now immediately interviewer will try to confuse you like does set implementation always follow this rule it will not allow duplicate then at the time you need to answer no there is some certain rule if that is not followed by any of the haset or any of the set implementation or map implementation then it will allow duplicate object now let me explain you that scenario let's say I have a student class let's let me go to the project I have a student class here right I have ID name and I have um this Constructor and I have getter seter two string method now what I'll do I'll just create this student object go to the uh where I added customer list right so here what I'll do I will just add student object to this haset or any implementation okay just remove this just create this let's say one not one let me add some duplicate I just want to show you the difference fine now I just want to add this set do add S1 there is something wrong in my ID S1 then let me add S2 and S3 S3 now let me print this set as per rule this set will not allow this duplicate right S1 and S2 to duplicate object here so it should print only one of them and S3 now if I run this let's wait for the output you can see all the three object one 1 again duplicate object one1 then the third object we should get two result right but we are getting three it means set is not following the rule it is allowing the duplicate right so there is a difference if the if you are using set with any primitive then it's fine you don't need to override and equals and has code method but if you're using any custom object or rapper class any custom object like student then you must need to override equals and hcode Method so you need to override equals let me add it finish okay now my student class overwrite this equals and hcode Method now if I run this the same code I'm running I was just trying to print the set now you're are getting two object it means even though you are using set or has map there is no guarantee that it will not allow duplicate but yes if your custom object is override equals and has code method if they follow the contract of equals and has code then always you'll get the unique object okay there will be no duplicate so this is one of the interview question to explain the contract between equals and has code method as well okay hope this concept is clear for you now the next question will be if you'll go to the slide what is the difference between comparable and comparator we will not go through the theory also I will explain you with the example when to use comparable and when to use comparator okay now if we'll go to the next slide there is a BAS basic difference so you can explain comparable provides a single sorting sequence where comparator provides multiple sorting sequence let's say I have an employee class and I have field called ID name and salary if I want to sort on based on ID or name or salary then I can go for single sorting sequence using comparable if I want to sort with the multiple parameter then with the help of comparable we cannot achieve it we need to go for comparator okay and comparable interface contains a method called compare two method to sort an element but comparator provides a compare method with two argument to sort an element if you are using comparable then it affects the original class let's say I have employee class then in employee class I need to implements from comparable that signature you need to write in the employee class and you need to overwrite the comparable method but if you're using comparator then you can create a separate class and implements from comparator then you can use this collections utility method sort method you can pass the list argument to sort that okay now let's understand this comparable and comparator with code so let's go to the intelligent already we created this student class right not this one we created this student class so let me close all go to the project open this student class now in student class I have two field ID and name I just want to sort based on ID so what I can do using comparable I can do it if I use comparable then it will directly affect in my actual class which is student so what I need to do I just need to type implements comparable okay and it is type generic you can pass your class type I'll pass student okay now it is GR it is forcing me to override the compare two method just override it okay let's take it up I'll add it here okay before two string so inside this compareed to Method you need to write the logic since I have the student object with me I can provide the Sorting either for ID or for name I cannot provide for both using comparable that's why it's single sorting uh implementation so what I can do I can simply write if ID equal equal to object do ID if both are same then return one sorry return zero because it's not greater than or I can write El if okay ID if it is greater than um o. ID sorry not zero o. ID better you can rename it to student s so that there will be no confusion make it s if it is greater than then just return one if it is less than directly I can add in else return return minus one okay just remove it fine now I added compare two method and I provided sorting based on the ID so let me change okay this is there 109 109 105 1 95 okay now what I'll do I added I created a list and I I added this three student object okay I'm printing it let me run this what's going wrong okay so we didn't add this to the list right so that's why students uh do add S1 similarly I would I will add for 2 three copy this b v okay S2 and S3 sorry fine so I created three student object and I also implements comparable and I override the compare two method and I provided um sorting based on the ID and now I added it to the list and I was trying to print it now if you'll run it you will not get a sorting order so I just want to show that see the way we added 1 195 we are getting in the same model so it should display one1 then 1059 why it's not displaying because we need to use this collections do sort then pass this list which is students right pass it now if I run this code I was getting on sorting order one1 then one5 and9 now in future I got a requirement no don't use this ID change sorting algorithm based on name now again I need to change this code right I just need to implement for the name so then in case of comparable it's not Dynamic it's always hardcoded today based on IDE implemented tomorrow I need uh based on the name I need to change the entire implementation which is not recommended that's why it's always recommended if you know you you are going to follow a single in algorithm then go for this comparable now when to use comparator let's say I will create based on ID and name okay let's say I created a Java class something called ID uh comparator okay not it then I just Implement from comparator pass the object as student I just want to make it generic if today I want based on the ID I can use this ID comparator if tomorrow I want based on the name I can use another comparator rather than hard code in the same class or your target class okay so what I'll do I'll just override a compare method compare method just override it fine so inside this method I can place the same logic just add it instead of ID what I will do I just make it S1 and say second object as S2 okay so you can write here S1 dog ID just remove this s2. get ID okay get ID similarly you can add it here S1 dog ID greater than then s2. get ID like so this is how you can write for ID comparator now let's say I just want to write a name comparator asual so what I can do I'll directly write Java class I'll write name comparator also Implement same from comparator pass the type generic which is nothing student then just overwrite the compare method here I can simply write S1 dog sorry this need to be changed or else o1 do get name get name do compareed to S2 do get sorry this is O2 I didn't change the reference name get name fine now I have two comparator ID comparator as well as name comparator now let's go to the code let me go to the student class now today I want to sort based on the name so what I can pass here simply I can pass new name comparator there is wrong in my ID new name comparator fine now if you will run your code it will sort based on the name not ID so basant B then P then s right now if you want again based on the ID you want you can change it to the ID comparator right now run this code 1 not1 5 9 okay so let me add one more field so that we can find the difference let's say something uh 98 okay and I added as now let me run based on the ID I should get this first let's run this okay four and also add that to the list students do R S4 now let's run this it sort based on the ID right now if I sort based on the name again just change it to the name comparator run it okay it's not working something going wrong let me go to the name comparator there is O one.get name compared to O2 dog name this is correct now go to the student okay so this should be Capital right because all the character we added capital and here we are adding the uh lower case so that's the reason we are getting this now let me run this we using name comparator yeah we getting it right a then starts with B then P then and SOS now let's assume we created separate comparator name comparator and ID comparator for multiple sorting using comparator interface now the next question from the interviewer which is a common interview question I can say I personally faced it so I just want to sort based on the ID if we found both the ID is same then I just want to go with the name setting so what I can do so let's go to this ID comparator here only you can uh do this logic if you found both the ID is same then simply go and sort based on the name S1 dot get name do compared to S2 do get name right so this comparator basically sort based on the ID if it found both the ID of object is same then it will sort based on the name this kind of scenario also we may need in future or while implementing a application right now if you go to the student let me change something let's say I'll add one more object with the same name let's say SP ID is same then I just want to add something b k because Okay add it to the list five now I just need to pass this ID comparator you can change the name because we are not going to sort based on the ID we are comparing based on ID if we found it is equal then we are sorting based on the name fine now let me run this code 98 we are getting the first then if You observe one1 bant then one1 because so what happened initially it found one1 and one1 both the object having the same ID then again it s based on the name b then the next character is a where it is B and the next character is I so he started comparing between this a and I so a comes first so he added this element I comes next to the a so he added it here okay so this is how you can provide your custom setting using comparator which is not not possible using comparable interface fine I hope this concept is clear for you when to use comp comparable and comparator now if you'll go to the next Slide the next question will be multic comparing using comparator scenario which we just understand we found based on ID if it is same then uh compare based on name right then the next question will be what is the difference between fail fast and fail safe iterator okay now a iterator which will fail fast when you do any modification while iterating a collection is called fail fast it iterator let's say I have one collection and I was trying to iterating it while iterating in middle I am trying to modify something on the same collection object then we'll get some exception which is concurrent modification exception that's the reason it is called fail fast iterator okay now the iterator who allow us to modify in middle while iterating a collection is called non fail first iterator or you can term it as a fail safe iterator the example copy and right AR list copy and right R set concurrent hmap these are the introduced in Java U concurrent package now let's understand this fail fast and fail safe iterator with one example now let me go to the intell ID let me close this so I have one fail first list so if You observe in this code I created one list of string and I added two element A and B okay and I I was using the iterator to iterate this uh list of string so if You observe here I was just printing it then I'm just printing it and I was adding one more element while iterating now one thir is iterating and I'm trying to add something in Middle okay now if I run this code I'll get concurrent modification exception the reason here internally this it iterator used a concept called mod count okay so any changes on the collection will be reflected in the mod count it will change at end it will evaluate this mod count if there is a changes found in mod count initially let's assume the mod count size uh assigned to the zero and here I was adding something then the mod count got changed to one if there is any difference found in mod count then immediately it will throw the concurrent modification exception so to prove it what I can do let me go to this uh yeah so if You observe there is something called mod count if not equal to expected mod count then we'll get the concurrent modification exception now if you'll go to this mod count initially it assigned to zero if you change anything in your uh collection then immediately it will increment by one so the it lost the actual value so we are getting the based on the condition let me go back based on condition this if will return true because it got changed after adding something to my list so we are getting this concurent modification exception now how can I aboid this so to that just use copy and write AR list now if I run it we are getting the result while iterating I can able to modify that is what this is called fail safe iterator or non fail fast iterator okay now you might have question then how it works on this copy and WR ARR list whether it is going to check the mod count or not yes it is going to check the mod count but if there is difference in mod count immediately it will create a clone copy of your collection and any update will happen to that cloned object instead of this actual collection object okay so to prove that so if You observe here I used copy and WR AR list and I added this list. add C okay but it will not print because there will be two iteration as you have two element A and B so we'll get these two statement next while iterating only we are adding one more one more element so there will be a next iteration but there will be only in output we can see only two iteration it means it's not adding to this list object okay it will add to the copy of list object because it will not print so let me run this yeah we are getting only A and B Because while iterating only we are adding this to the list now the list index size will be three so there will be three iteration but still we are getting only two iteration value right it means internally it used one copy object when there is different in mod count okay now similarly if you'll go to the uh fail first map so I created one uh map called uh has map I added these two entry and I was iterating it then in middle I was adding it okay now let me run this I will get exception not this one let me close this now to aboid that what you can do instead of H map let's use concurrent H map okay now if I'll run this code there will be no Error 1 2 3 1 2 but in case of this congruent has map map it is not using the cloned copy of your collection implementation either list or map since we are using map here there will be no copy so if You observe we are getting these three as well but in previous example we are getting only a b we are not getting this value because it return a clone copy of your collection even though there is a mod count change but in map the implementation is different okay there is no clone clone copy concept so use concurrent has map whenever you want to access through parallel thread while iterating uh you want to modify something then you can go for concurrent has map okay so you can see this output 1 2 3 even though we are using concurrent has map there is no cloned copy return from the map implementation I'll tell you how it works in concurrent H map in upcoming slide there is some slide locking mechanism difference that's how we are not getting exception uh using concr H map even it is not using any clone copy okay so we'll discuss that in coming slide now the next question from the interviewer will be let's go to the slide the next question can be what is the need of concr H map and how it is different from has map just to understood the use of concurrent has map right now to answer this you can say has map is non-synchronized where multiple thread can access parallely where concurrent has map is synchronized and you can say has map is non- thread saap or concurrent has map is thread saap and just to observe this has map is fail fast right it throws concurrent modification exception but if you'll use concurrent hmap it is fail safe there is no exception called concurrent modification exception if you're using any concurrent implementation it can be uh concurrent has map or copy and right ARR list copy and right reset now in has map it allow for storing null keys and value in has map map you can add null key and value but in case of concurrent has map it will not allow to add key or value as a null it will immediately through null pointer exception I'll show you that in internal code now the performance is faster in case of hmap since it supports nonsynchronized where the concurrent has map is slow as compared to the has map now let's understand how this thread safety and nonre non-thread safety is there in h map and concr H map and also the first two you understood fail first and fail safe using this has map and concr H map right now let's understand how these two are different practically now let me go to the intellig ID go to the project so there is a class I created called custom thread now let me go there so if You observe I created one thread okay created a class called custom thread I extended from thread and I created one map object okay if you see the implement impementation is has map and here I overwrite the wrong method inside the wrong method just print the thread do sleep for uh 1,000 millisecond now I was just adding some element to the map so globally I declare one map object and this is one child thread right because there is a main thread this is my main thread and this is what I extend from thread so this will act as a my child thread so inside child thread I was adding I was trying to add something to the map okay now go to the main thread this is what my main thread inside the main thread I added 1 1 not1 one2 ABC okay so then I created thread object okay then from Main thread I was trying to trying to iterating but another thread is trying to insert something okay now if I run this code I should get concurrent modification exception okay okay so if You observe I was getting congruent modification exception because one thread is trying to iterating it which is nothing my main thread and another thread which is child thread is trying to add something in the same time that's what we are getting concurent modification exception because we are using has map and what happened internally this map apply logs on entire object now this map object is logged so that's the the reason one thread is iterating it got locked it will not allow other thread to do something that's the reason we are getting concurrent exception in case of U map implementation has map okay now simply I will change it to concurent has map fine now let me run this code you'll get the output there will be no exception see we we are getting all the record right a BC and this is added by my child thread so whenever we are using concr house map it allow multiple thread to access simultaneously they can able to modify my underlaying collection data structure there will be no exception the reason here in case of concr house map it apply it does not apply lock on the entire map object it apply lock on the segment level so let's say you are iterating it okay now I iterate the first entry so since it start from zero my first entry will be this so you try iterating this map this 100 and a in Middle thread context switching happened then immediately it go there and it added another object okay because you don't know which thread will execute first parent or child that will be depends on your thread SED okay then again he released the lock it started adding um another entry then again it started adding another entry and what concr has map does it just apply lock on the segment label rather than apply lock on the entire underlaying collection object that's the reason we are not getting any exception if you're using concurrent hashmap so the main hash map is non-synchronized and concurrent hash map is synchronized and has map apply the lock on entire object where congruent has map apply the lock lock based on the segment so that is called segment locking or bucket locking in concurrent house map now if you'll go to the slide we understand one more Point has map it allow for storing null keys and value where concurrent has map does not allow so to prove that let's go to the intellig go to the project hope this is clear right how map has Map works and how concurent has map how it differs based on the locking mechanism now if you'll go to the null key value If You observe I created a map and I added um key as a null value as a null now if I'll print it it will give me null null okay there will be no exception now if I'll change it to the concurrent H map I'll get the exception null pointer exception we are getting null pointer exception now if you'll go to this implementation see there is a uh filter condition if key equal equal to null or any of them value equal equal to null null then immediately through this null pointer exception but this is not there in hmap okay now let me go back to the code fine now the next question from the interviewer if we'll go back to the slide we understand this concurrent H map is synchronized right but interviewer can ask if we have has table which is already synchronized then why we need concurrent has map because has table is is already synchronized and still this concurent H map is also synchronized then what is the difference between these two so you can simply answer to the interviewer even though has table is synchronized but the locking mechanism is still same as for has map it will lock whole underling data structure there will be no segment locking or bucket locking in har table okay because of this locking mechanism it's always preferable to use concurrent has map rather than has table so if you can see this diagram this as table apply lock on Entre map object right ENT table but in concr has map it apply lock on the segment Segment 1 2 3 4 or you can say this is a bucket of a map okay in each bucket it will apply the lock not in all object okay now the next question you can find that's fine we can ignore H table but also there is a option in Java we can synchronize our H map using collections do synchronized map right there is a syntax in collections utility class we can use collections. synchronized map and you can synchronized our map then why we need concr has map because either way we are achieving the synchronization right again you can say if you'll use this collections. synchronized map that will act as a has table again and again there will be a difference between locking mechanism between this synchronized map and concurrent has map so this you can answer to the interviewer you need to convince them okay then the next question will be how hmap internally works so if you'll attend 10 interview then most probably you'll get this question nine times okay now to explain this question what I can do I created an animation which will help you to understand this hmap internal flow okay now let's say I created one map object okay when you created a has map object internally it create a bucket structure like this since initial capacity of map is 16 initially it will create 16 bucket so if You observe here 0 1 2 3 4 5 up to 15 index begin from zero and it end with 15 right so it created 16 bucket each bucket internally uses a linked list so in this 15 bucket bucket 0 1 every bucket is considered as a linked list okay and this linked list contains on node okay now if You observe see the internal structure of node it contains key value H and next okay so it means each bucket can be considered as a linked list and each linked list or each bucket can have n number of node okay so and that node structure will be key value has and next fine we created map object now let's create few employee object to store in map so I created here for employee object now when I put map dop put E1 and then some string value E1 is nothing my employee one object now how your has map will identify this entry where you need to keep this entry between this 0 to 15 right so what hmap internally do when we internally call this put method inside the put method there is a method called has okay it will take the argument is your key my key is nothing employee one object so it will pass this has function and it will evaluate some has value and then based on the modular operator it will identify the index for example let's assume this first entry it evaluate index 6 now simply this entry or this node will go and store in bucket 6 my bucket 6 is nothing a linked list and it store one node as I mentioned above the high level diagram this node contains key which is nothing the E1 and value is nothing my DV then some has value and if You observe the last bucket or the last entry is null because there is no more element in this bucket so there is no pointer so that's the reason it is null okay now similarly let's assume I'm trying to add my second object okay and again it come to the put method and it evaluate the has then it evaluate the index let's assume it evaluate the index as nine now simply this node will go and store in my bucket 9 so if You observe again it store key value has then next reference which is null because there is no element in this bucket okay now third time let me try to add this E3 okay with some different string again it come to the the put method and evaluate the has then it find the index coincidentally let's assume that it find the same index which is six now if you'll go and check in six there is already one node now in the same entry or in the same uh linked list if if you'll find multiple node or you can say if in a same bucket if you'll find multiple node then that concept is called Hing Collision okay so in that Hing Collision d directly my map will not add this entry to the bucket number which is evaluated by this Index right which is six so what it will internally do since both having the same has so it placed on the same bucket immediately map go and check the equals method to check the content wise both are different or same so it will go and check E2 do equals E3 okay because already sorry this should be E1 because E1 is already there in bucket right E1 equals E3 if it find different then immediately it will store that entry to the same bucket which is nothing the six and now this will not be null this will be the next reference it means in the bucket six there will be two node this one is the E1 is the first node and E3 is the next node so that's the reason E1 next point to the second node okay so this is placed in six only I don't have space so I added it down so don't consider this placed in seven bucket okay so it means if in a same bucket there is multiple node then this condition is called Hing Collision to avoid that Hing Collision map internally used double equal operator to check the reference if both are same reference or different reference if it found same reference it will just replaced if it found uh different reference then immediately it will go and check the content okay so content between E1 and and E3 okay E1 equals to E3 if it is true then again it will replace if it found different then it will just add as a next node right to the first node okay now we have one more element which is E4 right so I'm trying to add this map. put this entry okay again it come to the put method it will evaluate the has it will find the index let's assume it find the index 7 okay then that node directly go to the seven bucket okay now interviewer immediately ask you let's say I pass the key as a null okay in map I passed key as a null value as a null then where it will place because we cannot evaluate the H or index based on null right the straightforward answer for this tricky question direct directly you can say if key is null then that entry will be placed in the zero bucket okay that is fixed if there is null key then that entry will be placed in in the zero bucket so this is how H map internally works so you not you need to understand this high level link list node what it contains then with this diagrammatic way you can answer to the interviewer so that there will be no further question in h map okay now the next question from the interviewer you can expect if you mention Java eight then he can immediately ask you what is the enhancement done in hmap in Java it okay so to answer to the that you can uh specify initially this has map each bucket is used as a linked Lo linked list okay but in certain threshold it will convert it to the balanced tree mechanism that will not be linked list okay in Java it they used uh um balanced tree instead of Link list but in some certain threshold let's say there is a Hing Collision in the same bucket they found five node then immediately that link list will convert to the balance tree and then it will maintain the U balance between the node okay I am not very sure about the internal implementation of this balance tree you just have a look on the Google you'll find but at high level the implemented something called balance tree if there is a some uh threshold initially it will use Link list only but after after certain threshold it will convert it to the balance tree okay now at high level if you want to uh see the flow of this H map I found this uh image from the Google so it's not very clear but you can understand the flow so initially you added key value to the map then it find has code of the key okay based on that has function it will evaluate the index and it will place it if it there is a Hing Collision means if uh node is placed on the same bucket where already one bucket uh one node exist if there is Hing Collision if there is no Hing Collision then simply add to linked list as first node okay if there is a Hing Collision then go and check the equals with the existing key if both are same just replaced or overwrite if both are different then add it that's what we understand right this is where we have the Hing Collision E1 and E3 and it check E1 do equals E3 so this diagram makes sense right now the next question from the interviewer which we already discussed if K is null in h map then where that entry will store in map then next enhancement in Java of map okay then the next and last question how tree map internally works so we understand has map concurent has map internal flow now we need to understand how tree map internally works so if you use tree map any object you will add as a key will preserve the default sorting order right then how it is doing the default sorting order now to explain that what I can do I'll go to the the intellig uh I'll go to the test class I don't have any code to explain this but I can write something let's say I have something called map of string uh string of integer or string string then I'll write map equal to new tree map now if I add something called map. putut if I add here a then some value X some some random value okay now if I copy this I'll add one more entry this will applicable for Treet as well okay because both preserve the default sorting mechanism okay so let me add it D or I will change something some random value okay now what happened already one entry exist that is a which is key and value is XY Z now whenever you will try to add the second entry or second object as a key what uh this Tre map internally do it will just check D dot compared to D is nothing the key okay uh this um key second key compared to the first key which is a okay now this compareed to Method will always return integer so not this one so what happened here if D do compared to a if it is greater than okay let me add comment if it is greater than then it will just add in the right side and it will return positive one plus one you can say okay if it is less one sorry less than then immediately it will just add in the left side and how it will know whether it is is less than or greater than based on the return type if it will return minus one then it will be the D is less than a and it will keep inside the left side now for example how it will add so here D do compared to a let's assume we have already a uh there in our list or key okay it compar D do compared to a so D do compared to a will be always return the positive okay so simply it will add just right side to it D okay now let me add something uh let's say this is B some value now again it will compare B do compared to a so B do compared to a uh not B yeah B uh it will compare with the D right B do compare with the D will return minus one okay so it will just add B to the B sorry D okay there will be one additional yeah so it will just compare each uh object or each key and it will find if it is uh return the compared to Method return return plus one then then it will simply add in right side if it return return minus one then it will simple add in the left side so this is how it works now what I'll do I'll just print this map s out this map now let me run this we're getting first a then B sorry this one a b and d right key value so it's sorting based on the key so B is greater than a so it placed in right side and D is greater than uh B right so placed in right side you just Supple the order and try to understand the flow okay yeah so there is few more collection interview question I will cover that in my next tutorial with Java features that's all about this particular video guys thanks for watching this video meet you soon with A New Concept
Info
Channel: Java Techie
Views: 86,806
Rating: undefined out of 5
Keywords: Core Java Interview Questions, Java Interview Preparation, Java Interview Tips, Common Java Interview Questions, Core Java Q&A, Java Interview Answers, Java Technical Interview, Core Java Concepts, Java Developer Interview, Java for Beginners, Java Job Interview, Java Interview Techniques, Java Best Practices, javatechie, core java
Id: FFfJeb8Ec6Y
Channel Id: undefined
Length: 136min 14sec (8174 seconds)
Published: Fri Oct 20 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.