Showing posts with label core java interview question answer. Show all posts
Showing posts with label core java interview question answer. Show all posts

Tuesday, March 31, 2020

Difference Betwixt Hashmap As Well As Concurrenthashmap Inwards Coffee Collection

HashMap vs ConcurrentHashMap inwards Java
ConcurrentHashMap inwards Java is introduced every bit an alternative of Hashtable inwards Java, which is a synchronized collection class, that makes the master copy departure betwixt HashMap as well as ConcurrentHashMap which is 1 is non-synchronized , non-thread prophylactic and non for work inwards Concurrent multi-threaded surroundings piece ConcurrentHashMap is a thread-safe collection as well as intended to survive used every bit primary Map implementation specially for multi-threaded as well as Concurrent environment. Apart from thread-safety, at that topographic point are or as well as thus subtle differences betwixt HashMap and ConcurrentHashMap which nosotros volition run into inwards this article. By the way, Difference betwixt HashMap as well as ConcurrentHashMap also every bit ConcurrentHashMap vs Hashtable are 2 pop core Java interview question, generally asked on senior score Java programmers.



Difference betwixt HashMap as well as ConcurrentHashMap inwards Java

In this section, nosotros volition run into or as well as thus to a greater extent than details virtually HashMap as well as ConcurrentHashMap as well as compare them on diverse parameters similar thread-safety, synchronization, performance, stay of work etc.



1) As I said the before get-go meaning departure betwixt HashMap and ConcurrentHashMap is that afterwards is thread-safe as well as tin survive used inwards a concurrent surroundings without external synchronization. Though it doesn't render the same score of synchronization every bit achieved past times using Hashtable but it's plenty for the most practical purpose.

2)You tin brand HashMap synchronized past times wrapping it on Collections.synchornizedMap(HashMap) which volition render a collection which is almost equivalent to Hashtable, where every alteration functioning on Map is locked on Map object piece inwards illustration of ConcurrentHashMap, thread-safety is achieved past times dividing whole Map into dissimilar sectionalization based upon Concurrency level as well as entirely locking particular part instead of locking the whole Map.

 ConcurrentHashMap inwards Java is introduced every bit an alternative of  Difference betwixt HashMap as well as ConcurrentHashMap inwards Java Collection3) ConcurrentHashMap is to a greater extent than scalable as well as performs meliorate than Synchronized HashMap in the multi-threaded surroundings piece inwards Single threaded surroundings both HashMap and ConcurrentHashMap gives comparable performance, where HashMap entirely slightly better.


In Summary Main departure betwixt ConcurrentHashMap and HashMap inwards Java Collection turns out to survive thread-safety, Scalability, as well as Synchronization. ConcurrentHashMap is a meliorate alternative than synchronized HashMap if you lot are using them every bit cache, which is the most pop work illustration of a Map inwards Java application. ConcurrentHashMap is to a greater extent than scalable as well as outperforms when a release of reader threads outnumber the release of author threads.

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

How To Traverse Iterate Or Loop Arraylist Inwards Java

How to Loop ArrayList inwards Java
Iterating, traversing or Looping ArrayList inwards Java agency accessing every object stored inwards ArrayList together with performing simply about operations similar printing them. There are many ways to iterate, traverse or Loop ArrayList inwards Java e.g. advanced for loop, traditional for loop amongst size(), By using Iterator together with ListIterator along amongst piece loop etc. All the method of Looping List inwards Java too applicable to ArrayList because ArrayList is an essentially List. In side yesteryear side department nosotros volition run across code example of Looping ArrayList inwards Java.



Loop ArrayList inwards Java – Code Example
 inwards Java agency accessing every object stored inwards  How to traverse iterate or loop ArrayList inwards JavaNow nosotros know that at that spot are multiple ways to traverse, iterate or loop ArrayList inwards Java, let’s run across simply about concrete code example to know precisely How to loop ArrayList inwards Java. I prefer advanced for loop added inwards Java 1.5 along amongst Autoboxing, Java Enum, Generics, Varargs together with static import, too known every bit foreach loop if I convey to simply iterate over Array List inwards Java. If I convey to take away elements piece iterating than using Iterator or ListIterator is best solution.



import java.util.ArrayList;
import java.util.Iterator;

/**
 * Java programme which shows How to loop over ArrayList inwards Java using advanced for loop,
 * traditional for loop together with How to iterate ArrayList using Iterator inwards Java
 * payoff of using Iterator for traversing ArrayList is that you lot tin give the axe take away
 * elements from Iterator piece iterating.

 * @author
 */

public class ArrayListLoopExample {

 
    public static void main(String args[]) {
 
        //Creating ArrayList to demonstrate How to loop together with iterate over ArrayList
        ArrayList<String> games = new ArrayList<String>(10);
        games.add("Cricket");
        games.add("Soccer");
        games.add("Hockey");
        games.add("Chess");
     
        System.out.println("original Size of ArrayList : " + games.size());
     
        //Looping over ArrayList inwards Java using advanced for loop
        System.out.println("Looping over ArrayList inwards Java using advanced for loop");
        for(String game: games){
            //print each chemical constituent from ArrayList
            System.out.println(game);
        }
     
        //You tin give the axe too Loop over ArrayList using traditional for loop
        System.out.println("Looping ArrayList inwards Java using uncomplicated for loop");
        for(int i =0; i<games.size(); i++){
            String game = games.get(i);
        }
     
        //Iterating over ArrayList inwards Java
        Iterator<String> itr = games.iterator();
        System.out.println("Iterating  over ArrayList inwards Java using Iterator");
        while(itr.hasNext()){
            System.out.println("removing " + itr.next() + " from ArrayList inwards Java");
            itr.remove();
        }
     
         System.out.println("final Size of ArrayList : " + games.size());
   
    }

}

Output:
master copy Size of ArrayList : 4
Looping over ArrayList inwards Java using advanced for loop
Cricket
Soccer
Hockey
Chess
Looping ArrayList inwards Java using uncomplicated for loop
Iterating  over ArrayList inwards Java using Iterator
removing Cricket from ArrayList inwards Java
removing Soccer from ArrayList inwards Java
removing Hockey from ArrayList inwards Java
removing Chess from ArrayList inwards Java
final Size of ArrayList : 0


That's all on How to iterate, traverse or loop ArrayList inwards Java. In summary role advance for loop to loop over ArrayList inwards Java, its short, construct clean together with fast but if you lot postulate to take away elements piece looping role Iterator to avoid ConcurrentModificationException.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Difference betwixt TreeMap together with TreeSet inwards Java

Difference Betwixt String Too Stringbuffer Inwards Java

String vs StringBuffer inwards Java
String as well as StringBuffer are 2 classes which are most widely used inwards whatsoever Java program. If I state yous tin non write a plan without using String inwards Java as well as thence it would non hold out an exaggeration. The string is everywhere, the String is concluding inwards Java; every functioning e.g. converting String into Uppercase, creating SubString,  converting String to Lowercase all effect inwards a split upwards novel String Object, which tin convey trigger frequent garbage collection as well as touching your application performance. hither comes StringBuffer in Java which is a mutable version of String, though it's non every bit characteristic rich every bit String and yous tin non piece of job StringBuffer in house of String but StringBuffer should hold out used whenever yous are performing String concatenation instead of String inwards Java.

In this Java tutorial, nosotros volition run into roughly divergence betwixt String and StringBuffer, which makes StringBuffer ideal choice for performing String operations.By the way, if yous went through whatsoever Java interview as well as thence yous must hold out familiar amongst this question, String vs StringBuffer is really popular Java interview question.



Difference betwixt String as well as StringBuffer inwards Java

Here is a listing of divergence betwixt StringBuffer as well as String , this is non a huge listing as well as barring pregnant divergence betwixt both of them yous don't bespeak to worry well-nigh remembering all those differences.




1) The commencement as well as most pregnant difference betwixt String as well as StringBuffer inwards Java is that String is immutable inwards Java piece StringBuffer is mutable. What this way is, performing whatsoever functioning on String volition create novel String object piece modifying StringBuffer object won't create a novel object.

2) If yous are using  + operator for concatenating multiple String then yous should non hold out worried much because  based upon Java implementation telephone telephone to the + operator is replaced amongst either StringBuffer or StringBuider based upon JVM implements Java 1.5 or lower version.

3) StringBuffer.append()method is used to perform String concatenation inwards Java.

4) Creating StringBuffer from String is easy, every bit StringBuffer accept a String input. Similarly converting StringBuffer to String is also slow past times using toString() method inwards Java.

5) Another pregnant divergence betwixt String and StringBuffer is that StringBuffer as well as String practise non part same type hierarchy, way yous tin non cast String to StringBuffer in Java. whatsoever such examine volition effect inwards ClassCastException in Java.


That's all on Difference betwixt String as well as StringBuffer inwards Java. The most of import divergence to recall betwixt String and StringBuffer is mutability.

 String as well as StringBuffer are 2 classes which are most widely used inwards whatsoever Java plan Difference betwixt String as well as StringBuffer inwards JavaIn Summary, yous should non create besides much String garbage if yous experience yous bespeak to alter a detail String to a greater extent than than oft than create a StringBuffer example as well as piece of job that. Using + operator for String concatenation is also a adept thought every bit it's clearer, concise as well as gives the same performance every bit using StringBuffer in Java. On in conclusion note, Consider using StringBuilder inwards Java five onwards.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Difference betwixt aspect as well as slumber inwards Java
Difference betwixt ArrayList as well as HashMap inwards Java
What is flat file inwards Java 
Difference betwixt TreeSet as well as TreeMap inwards Java
What is Serialization inwards Java

Top Eighteen Coffee Pattern Pattern Interview Questions Answers For Experienced

Design pattern interview enquiry inward Java
Both OOP together with GOF pattern pattern interview questions are an integral constituent of whatever proficient listing of gist Java interview questions. Java is a pop Object oriented programming linguistic communication together with has lots of pattern pattern together with pattern principles, contributed past times many developers together with opened upward source framework. As a Java programmer its expected from you lot to know OOPS concepts similar Abstraction, Encapsulation, and Polymorphism, What is pattern pattern inward Java, Some pop Java pattern pattern together with most importantly when to exercise those pattern pattern inward Java application. The purpose of bespeak pattern pattern interview enquiry inward Java is to cheque whether Java programmer is familiar amongst those essential pattern patterns or not.

Design patterns inward Java interviews are equally of import as multi-threading, collection, and programming questions. If you lot are senior or experienced Java programmer than expecting to a greater extent than complex together with tough pattern pattern inward Java interview e.g. Chain of Responsibility pattern pattern together with solving real-time software pattern questions.



Top Java pattern pattern questions together with answers

Here is my listing of top 10 pattern pattern interview enquiry inward Java. I have got too provided an respond to those Java pattern pattern enquiry equally a link. no affair which flat of Java interview is you lot going e.g. programmer, software engineer, senior software engineer inward Java, you lot tin hold off few enquiry from Java pattern pattern.

1. When to exercise Strategy Design Pattern inward Java?
Design pattern interview enquiry inward Java Top eighteen Java Design Pattern Interview Questions Answers for ExperiencedStrategy pattern inward quite useful for implementing laid of related algorithms e.g. compression algorithms, filtering strategies etc. Strategy pattern pattern allows you lot to exercise Context classes, which uses Strategy implementation classes for applying work concern rules. This pattern follows opened upward shut pattern regulation together with quite useful inward Java.

One of a proficient instance of Strategy pattern from JDK itself is a Collections.sort() method together with Comparator interface, which is a strategy interface together with defines a strategy for comparison objects. Because of this pattern, nosotros don't demand to modify sort() method (closed for modification) to compare whatever object, at the same fourth dimension nosotros tin implement Comparator interface to define novel comparison strategy (open for extension).


2. What is Observer pattern pattern inward Java? When exercise you lot exercise Observer pattern inward Java?
This is ane of the most mutual Java pattern pattern interview questions. Observer pattern is based upon notification, at that topographic point are 2 kinds of object Subject together with Observer. Whenever at that topographic point is alter on subject's solid put down observer volition have notification. See What is Observer pattern pattern inward Java amongst existent life example for to a greater extent than details.



3. Difference betwixt Strategy together with State pattern Pattern inward Java?
This is an interesting Java pattern pattern interview questions equally both Strategy together with State pattern has the same structure. If you lot facial expression at UML degree diagram for both patterns they facial expression just same, but their intent is totally different.

State pattern pattern is used to define together with deal the solid put down of an object, acre Strategy pattern is used to define a laid of an interchangeable algorithm together with let's customer direct ane of them. So Strategy pattern is a customer driven pattern acre Object tin deal their solid put down itself.



4. What is decorator pattern inward Java? Can you lot laissez passer an instance of Decorator pattern?
Decorator pattern is or hence other pop Java pattern pattern enquiry which is mutual because of its heavy usage in java.io package. BufferedReader and BufferedWriter are a proficient instance of decorator pattern inward Java. See How to exercise Decorator pattern inward Java for to a greater extent than details.


5. When to exercise Composite pattern Pattern inward Java? Have you lot used previously inward your project?
This pattern pattern enquiry is asked on Java interview non but to cheque familiarity amongst the Composite pattern but also, whether a candidate has the existent life sense or not.

The Composite pattern is too a gist Java pattern pattern, which allows you lot to process both whole together with constituent object to process inward a similar way. Client code, which deals amongst a Composite or private object doesn't differentiate betwixt them, it is possible because Composite degree too implement the same interface equally their private part.

One of the proficient examples of the Composite pattern from JDK is JPanel class, which is both Component together with Container.  When the paint() method is called on JPanel, it internally called paint() method of private components together with allow them describe themselves.

On the instant constituent of this pattern pattern interview question, last truthful, if you lot have got used together with then tell yes, otherwise tell that you lot are familiar amongst the concept together with used it past times your own. By the way, ever remember, giving an instance from your projection creates a amend impression.



6. What is Singleton pattern inward Java? 
Singleton pattern inward Java is a pattern which allows alone ane event of Singleton degree available inward the whole application. java.lang.Runtime is a proficient instance of Singleton pattern inward Java. There are lot's of follow upward questions on Singleton pattern encounter 10 Java singleton interview enquiry answers for those followups


7. Can you lot write thread-safe Singleton inward Java?
There are multiple ways to write thread-safe singleton inward Java e.g past times writing singleton using double checked locking, past times using static Singleton event initialized during class loading. By the means using Java enum to exercise thread-safe singleton is the most uncomplicated way. See Why Enum singleton is amend inward Java for to a greater extent than details.


8. When to exercise Template method pattern Pattern inward Java?
The Template pattern is or hence other pop gist Java pattern pattern interview question. I have got seen it appear many times inward existent life projection itself. Template pattern outlines an algorithm inward cast of template method together with lets subclass implement private steps.

The telephone commutation indicate to mention, acre answering this enquiry is that template method should last final, hence that subclass tin non override together with alter steps of the algorithm, but same fourth dimension private measurement should last abstract, hence that tyke classes tin implement them.


9. What is Factory pattern inward Java? What is the wages of using a static manufactory method to exercise an object?
Factory pattern inward Java is a creation Java pattern pattern together with favorite on many Java interviews.Factory pattern used to exercise an object past times providing static manufactory methods. There are many advantages of providing manufactory methods e.g. caching immutable objects, slowly to innovate novel objects etc. See What is Factory pattern inward Java together with benefits for to a greater extent than details.


10. What is the departure betwixt Decorator together with Proxy pattern inward Java?
Another tricky Java pattern pattern enquiry together with fox hither is that both Decorator together with Proxy implements the interface of the object they decorate or encapsulate. As I said, many Java pattern pattern tin have got similar or just same construction but they differ inward their intent.

Decorator pattern is used to implement functionality on an already created object, acre a Proxy pattern is used for controlling access to an object.

One to a greater extent than departure betwixt Decorator together with the Proxy pattern pattern is that Decorator doesn't exercise an object, instead, it acquire the object inward its constructor, acre Proxy genuinely creates objects. You tin too read Head First Analysis together with Design to empathize the departure betwixt them.


11. When to exercise Setter together with Constructor Injection inward Dependency Injection pattern?
Use Setter injection to furnish optional dependencies of an object, acre exercise Constructor iInjection to furnish a mandatory dependency of an object, without which it tin non work. This enquiry is related to Dependency Injection pattern pattern together with to a greater extent than oft than non asked inward the context of Spring framework, which is similar a shot perish a criterion for developing Java application.

Since Spring provides IOC container, it too gives you lot a means to specify dependencies either past times using setter methods or constructors. You tin too accept a facial expression my previous post on the same topic.


12. What is departure betwixt Factory together with Abstract Factory inward Java
I have got already answered this enquiry inward especial amongst my article amongst the same title. The principal departure is that Abstract Factory creates manufactory acre Factory pattern creates objects. So both abstract the creation logic but ane abstract is for manufactory together with other for items. You tin encounter here to respond this Java pattern pattern interview question.


13. When to exercise Adapter pattern inward Java? Have you lot used it earlier inward your project?
Use Adapter pattern when you lot demand to brand 2 degree piece of work amongst incompatible interfaces. Adapter pattern tin too last used to encapsulate 3rd political party code hence that your application alone depends upon Adapter, which tin suit itself when 3rd political party code changes or you lot moved to a dissimilar 3rd political party library.

By the way, this Java pattern pattern enquiry tin too last asked past times providing an actual scenario. You tin farther read Head First Design Pattern to larn to a greater extent than almost Adapter pattern together with its existent basis usage. The mass is updated for Java 8 equally good hence you lot volition larn new, Java 8 means to implement these one-time pattern patterns.

Design pattern interview enquiry inward Java Top eighteen Java Design Pattern Interview Questions Answers for Experienced


14. Can you lot write code to implement producer consumer pattern pattern inward Java?
The Producer-consumer pattern pattern is a concurrency pattern pattern inward Java which tin last implemented using multiple ways. If you lot are working inward Java v together with then its amend to exercise Concurrency util to implement producer-consumer pattern instead of plainly one-time wait together with notify inward Java.  Here is a proficient instance of implementing producer consumer work using BlockingQueue inward Java.


15. What is Open shut pattern regulation inward Java?
The Open shut pattern regulation is ane of the SOLID regulation defined past times Robert C. Martin, popularly known equally Uncle Bob inward his most pop book, Clean Code. This regulation advises that a code should last opened upward for extension but shut for modification.

Design pattern interview enquiry inward Java Top eighteen Java Design Pattern Interview Questions Answers for Experienced


At first, this may facial expression conflicting but ane time you lot explore the mightiness of polymorphism, you lot volition start finding patterns which tin furnish stability together with flexibility of this principle.

One of the telephone commutation examples of this is State together with Strategy pattern pattern, where Context degree is shut for modification together with novel functionality is provided past times writing novel code past times implementing a novel solid put down of strategy. See this article to know to a greater extent than almost Open shut principle.


16. What is Builder pattern pattern inward Java? When exercise you lot exercise Builder pattern?
Builder pattern inward Java is or hence other creational pattern pattern inward Java together with oft asked inward Java interviews because of its specific exercise when you lot demand to build an object which requires multiple properties or hence optional together with or hence mandatory. See When to exercise Builder pattern inward Java for to a greater extent than details


17. Can you lot laissez passer an instance of  SOLID pattern principles inward Java?
There are lots of SOLID pattern pattern which forms acronym SOLID e.g.
1. Single Responsibility Principle or SRP
3. Open Closed Design Principle or OCD
3. Liskov Substitution Principle
4. Interface Segregation Principle
5. Dependency Inversion Principle.

You tin farther read this list of SOLID pattern principles for Java programmer to respond this Java interview question.


18. What is the departure betwixt Abstraction together with Encapsulation inward Java?
Even though both Abstraction together with Encapsulation looks similar because both shroud complexity together with brand the external interface simpler at that topographic point is a subtle departure betwixt them. Abstraction hides logical complexity acre Encapsulation hides Physical Complexity.

Btw, I have got already covered respond of this Java interview enquiry inward my previous post equally Difference betwixt encapsulation together with abstraction inward Java, hither are or hence to a greater extent than departure from that post.

Design pattern interview enquiry inward Java Top eighteen Java Design Pattern Interview Questions Answers for Experienced


This was my listing of 10 pop pattern pattern interview enquiry inward Java. I have got non included MVC (Model View Controller) pattern pattern because that is to a greater extent than specific to J2EE together with Servlet JSP interview, but if you lot are going for whatever Java interview which demands sense inward J2EE together with then you lot must gear upward MVC pattern pattern. That's all on Java pattern pattern interview enquiry together with answers. Please allow us know if you lot have got whatever other interesting enquiry on Java pattern pattern.


Other Java interview questions post:
  • Java Questions for Phone Screen Interviews (list)
  • Hibernate Interview Questions amongst Answers (list)
  • Spring MVC Interview Questions together with Answers (list)
  • Java Enum Interview Questions together with Answers (list)
  • Thread together with Concurrency Questions from Java Interviews (list)
  • RESTful Web Service Interview Questions (list)
  • Java OOP Interview Questions amongst Answers (list)
  • Array Concept Interview Questions inward Java (list)
  • JDBC Interview Questions together with Answers (list)
  • Servlet together with JSP Interview Questions together with Answers (list)
  • Java Web Service Interview Questions together with Answers (list)

Further Learning
Design Pattern Library
From 0 to 1: Design Patterns - 24 That Matter - In Java
Java Design Patterns - The Complete Masterclass

Top X Coffee Collection Interview Questions Answers | Coffee Collection Faq

Java Collection Framework interview questions too answers incorporate questions from pop Java collection classes e.g. HashMap, ArrayList, HashSet, ConcurrentHashMap and legacy collection classes similar Vector and Hashtable. Interview questions from Java Collection framework are i of the most asked concepts on whatsoever Core Java interview or J2EE interview at both beginners, experienced too intermediate degree e.g. ii to four years experienced Java programmer. In guild to reply interview questions from Java collection framework, You demand a expert cognition of diverse Collection interfaces e.g. Map, List too Set too familiarities amongst their oftentimes used implementation e.g. HashMap, Hashtable, TreeMap from Map, ArrayList, LinkedList too Vector for List interface too HashSet, TreeSet of Set interface.

Questions related to Iterating collection, modifying Collection too thread-safety of Collection is too the pop expanse from where Java collection interview Questions asked during the interview.

In this List of Java collection interview questions too answers, nosotros volition run into questions from all higher upwards area. I accept too included or hence questions from novel Concurrent collection classes introduced inwards Java v e.g. ConcurrentHashMap and CopyOnWriteArrayList.



Java Collection Interview Questions Answers

 Java Collection Framework interview questions too answers incorporate questions from pop  Top 10 Java Collection interview Questions Answers | Java Collection FAQfrequently asked Questions from Java collection framework. Almost all of these questions accept appeared inwards Java interview at the diverse degree ranging from Junior to Senior Software Engineer degree at dissimilar Companies e.g. Capgemini, Tech Mahindra, TCS, Satyam, too CTS.



What is Difference betwixt Hashtable too HashMap inwards Java?
This Java collection interview interrogation is I estimate most pop one. Most of Java programmer who has at to the lowest degree ii years of sense has seen this interrogation on heart Java or J2EE interview. Well, at that topographic point is much divergence betwixt them simply most of import is thread-safety, HashMap is non thread-safe spell Hashtable is a thread-safe collection. See Hashtable vs HashMap inwards Java for to a greater extent than differences betwixt HashMap too Hashtable inwards Java.


What is the divergence betwixt Hashtable too ConcurrentHashMap in Java?
Another oftentimes asked Java collection interview interrogation post-Java v footing which introduced Concurrent Collection classes similar ConcurrentHashMap and CopyOnWriteArrayList along amongst Concurrency utilities e.g. CyclicBarrier too CountDownLatch. Well, both Hashtable too ConcurrentHashMap are thread-safe hither simply later on provides to a greater extent than scalability than former. See Difference betwixt ConcurrentHashMap too Hashtable inwards Java for the reply of this Java collection interview question.


What is Difference betwixt Iterator too Enumeration inwards Java?
One of the classic interview Questions asked on Java collection framework, This is pretty old too programmer who has been working inwards Java for four to half dozen years must accept seen this interrogation before. Well, Iterator too ListIterator inwards Java is a novel means to iterator collection inwards Java too provides the mightiness to withdraw an object spell traversing spell Enumeration doesn't allow you lot to withdraw the object. See Iterator vs Enumeration inwards Java for to a greater extent than differences betwixt both of them.


What is Difference betwixt fail-safe too fail-fast Iterator inwards Java?
This is relatively novel Java collection interview interrogation because the concept of a fail-safe iterator is come upwards along amongst ConcurrentHashMap and CopyOnWriteArrayList. See Difference betwixt fail-safe too fail-fast Iterator inwards Java for the reply of this Java collection question.



How HashMap industrial plant internally inwards Java?
One of the most oftentimes asked Java interview interrogation to sense Java programmer of four to v years of experience. I accept seen this interrogation on big companies similar Morgan Stanley, JP Morgan, Nomura too other banks e.g. Barclays Capital. See How HashMap industrial plant internally inwards Java for detailed reply of this Java collection interview question.


Can you lot write code to traverse Map inwards Java on four ways?
Another Java collection interrogation which appears equally role of Java Coding interview question too appeared inwards many interviews. As you lot know at that topographic point are multiple ways to traverse or iterate Map inwards Java e.g. for loop, spell loop using Iterator etc. 4 ways to iterator Map inwards Java has detailed explanation too sample code which is sufficient to reply this Java collection framework interview question.


What is the divergence betwixt Vector too ArrayList inwards Java?
Along amongst Difference betwixt HashMap too Hashtable, this Java collection interview interrogation is belike instant inwards the listing of oftentimes asked interrogation on Java collection framework. Both ArrayList too Vector implements List interface from Java four simply they accept differences including synchronization, See the difference betwixt Vector too ArrayList inwards Java for the consummate reply of this collection interview interrogation inwards Java.


What is the divergence betwixt ArrayList too LinkedList inwards Java?
H5N1 follow-up interrogation which is asked inwards response to previous Java collection interview question. Here too both LinkedList too ArrayList are List implementation simply their internal data-structure is different, i is derived from Array spell other is derived from LinkedList. See LinkedList vs ArrayList inwards Java to reply this Java Collection interview question.



What is the divergence betwixt List too Set inwards Java?
List vs Set is i of the most of import concepts to empathize inwards Java Collection framework too this Java collection interview question focus on that. Most of import divergence betwixt them is that List allows duplicates too keep insertion guild spell Set doesn't allow duplicates too doesn't keep whatsoever order. See Difference betwixt Set too List inwards Java to run into to a greater extent than differences betwixt them.

Here is too a dainty summary of dissimilar collection classes inwards Java:

 Java Collection Framework interview questions too answers incorporate questions from pop  Top 10 Java Collection interview Questions Answers | Java Collection FAQ



How produce you lot respect if ArrayList contains duplicates or not?
Since List allows duplicates this becomes a followup interrogation of before Java collection framework interview question. See How to cheque if ArrayList contains duplicates or not for the reply of this Java collection question.

That's all almost or hence of the oftentimes asked Java Collection interview questions. Btw, If you lot accept whatsoever interesting Java collection interview interrogation or are you lot looking an reply for whatsoever Java collection interrogation hence delight post service here. If you lot are looking for or hence assistance, you lot tin ship away too cheque out the Java Programming Interview Exposed book past times Noel Markham, an ideal take to ready for Java developer interviews. 

 Java Collection Framework interview questions too answers incorporate questions from pop  Top 10 Java Collection interview Questions Answers | Java Collection FAQ

These were or hence of the frequently asked Java collection framework interview questions you lot tin ship away too telephone telephone them Java Collection FAQ. Collection too Threads are most of import role of Java programming linguistic communication too considered equally fundamentals of Java, So ever ready them good before appearing for whatsoever Java or J2EE interview

Further Learning
Java In-Depth: Become a Complete Java Engineer
10 tough Core Java interview questions too answers
133 Core Java Interview Questions from concluding v years

Thanks for reading this article hence far. If you lot similar these interview questions hence delight part amongst your friends too colleagues. If you lot accept whatsoever interrogation or feedback hence delight drib a comment.

What Is Copyonwritearraylist Inwards Coffee - Illustration Tutorial

CopyOnWriteArrayList vs Array List inwards Java
CopyOnWriteArrayList is a concurrent Collection course of didactics introduced inwards Java five Concurrency API along amongst its pop cousin ConcurrentHashMap inwards Java. CopyOnWriteArrayList implements List interface similar ArrayList, Vector, as well as LinkedList simply its a thread-safe collection as well as it achieves its thread-safety inwards a slightly dissimilar agency than Vector or other thread-safe collection class. As the cite suggests CopyOnWriteArrayList creates a re-create of underlying ArrayList amongst every mutation functioning e.g. add, remove, or when y'all prepare values. That's why it is exclusively suitable for a modest listing of values which are read oftentimes simply modified rarely e.g. a listing of configurations.

Normally CopyOnWriteArrayList is rattling expensive because it involves costly Array copy amongst every writes functioning simply it's rattling efficient if y'all convey a List where Iteration outnumbers mutation e.g. y'all by as well as large take to iterate the ArrayList as well as don't alteration it also often.

Iterator of CopyOnWriteArrayList is fail-safe as well as doesn't throw ConcurrentModificationException fifty-fifty if underlying CopyOnWriteArrayList is modified 1 time Iteration begins because Iterator is operating on a dissever re-create of ArrayList. Consequently, all the updates made on CopyOnWriteArrayList is non available to Iterator (see thread-safety past times creating a dissever copy of List for each writes operation.

Now let's run into Some deviation betwixt ArrayList as well as CopyOnWriteArrayList inwards Java, which is roughly other implementation of List interface :


1) First as well as inaugural of all deviation betwixt CopyOnWriteArrayList as well as ArrayList inwards Java is that CopyOnWriteArrayList is a thread-safe collection acre ArrayList is non thread-safe as well as tin non last used inwards the multi-threaded environment.

2) The bit deviation betwixt ArrayList as well as CopyOnWriteArrayList is that Iterator of ArrayList is fail-fast as well as throw ConcurrentModificationException 1 time uncovering whatsoever modification inwards List 1 time iteration begins simply Iterator of CopyOnWriteArrayList is fail-safe as well as doesn't throw ConcurrentModificationException.

3) The 3rd deviation betwixt CopyOnWriteArrayList vs ArrayList is that Iterator of onetime doesn't back upwards take functioning acre Iterator of afterwards supports remove() operation.  If y'all desire to acquire to a greater extent than almost collections, I advise y'all perish through Complete Java MasterClass, 1 of the best Java course of didactics on Udemy.



CopyOnWriteArrayList Example inwards Java

CopyOnWriteArrayList vs Array List inwards Java What is CopyOnWriteArrayList inwards Java  - Example TutorialHere is a consummate code Example of CopyOnWriteArrayList which demonstrate that Iterator of CopyOnWriteArrayList doesn't back upwards remove() operation.

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 *
 * Java computer program to demonstrate What is CopyOnWriteArrayList inwards Java,
 * Iterator of CopyOnWriteArrayList
 * doesn’t back upwards add, take or whatsoever modification operation.
 *
 * @author
 */

public class CopyOnWriteArrayListExample{

    public static void main(String args[]) {
     
        CopyOnWriteArrayList<String> threadSafeList = new CopyOnWriteArrayList<String>();
        threadSafeList.add("Java");
        threadSafeList.add("J2EE");
        threadSafeList.add("Collection");
     
        //add, take operator is non supported past times CopyOnWriteArrayList iterator
        Iterator<String> failSafeIterator = threadSafeList.iterator();
        while(failSafeIterator.hasNext()){
            System.out.printf("Read from CopyOnWriteArrayList : %s %n", failSafeIterator.next());
            failSafeIterator.remove(); //not supported inwards CopyOnWriteArrayList inwards Java
        }
    }
}

Output:
Read from CopyOnWriteArrayList : Java
Read from CopyOnWriteArrayList : J2EE
Read from CopyOnWriteArrayList : Collection



If nosotros uncomment, commented code inwards this Java program which modifies CopyOnWriteArrayList using Iterator thence nosotros volition acquire next Exception :

Read from CopyOnWriteArrayList : Java
Exception inwards thread "main" java.lang.UnsupportedOperationException
        at java.util.concurrent.CopyOnWriteArrayList$COWIterator.remove(CopyOnWriteArrayList.java:1004)
        at test.CollectionTest.main(CollectionTest.java:29)
Java Result: 1

Here is a summary of CopyOnWriteArrayList inwards a slide, it teaches y'all what all the words convey taught y'all thence far:

CopyOnWriteArrayList vs Array List inwards Java What is CopyOnWriteArrayList inwards Java  - Example Tutorial


That's all almost what is CopyOnWriteArrayList, the deviation betwixt CopyOnWriteArrayList as well as ArrayList inwards Java as well as an illustration of CopyOnWriteArrayList. In short, purpose CopyOnWriteArrayList if y'all by as well as large require to Iterate over listing without modifying it.



Further Learning
Java In-Depth: Become a Complete Java Engineer
10 must know Java Collection interview query for two years sense programmer

Thanks for reading this article thence far, if y'all similar this article thence delight percentage amongst your friends as well as colleagues. If y'all convey whatsoever feedback or questions thence delight drib a note. 

Monday, March 30, 2020

What Is Divergence Betwixt Interface In Addition To Abstract Flat Inward Java

What is abstract cast in addition to interface inwards Java
The departure betwixt abstract cast in addition to interface inwards Java is 1 of the tricky Java interview question in addition to generally look inwards center Java interviews. It has choke at 1 time fifty-fifty trickier after Java 8 introduced default methods in addition to allowed interfaces to convey both default in addition to static methods. Even though both interface in addition to abstract cast is a way to give abstraction inwards Java, there are meaning differences betwixt them, which you lot volition acquire inwards this article. Some fourth dimension interviewer besides non simply focus on fundamental differences betwixt abstract cast in addition to interface inwards Java but he is besides interested inwards unopen to practical sense e.g. when to occupation interface inwards Java in addition to when to occupation abstract cast is Java. This is genuinely the tricky component subdivision of this interview query and  you lot must convey a skilful agreement of what is an interface in addition to abstract cast inwards Java in addition to how to occupation them. Anyway inwards this Java article nosotros volition outset come across unopen to syntactical difference betwixt interface in addition to abstract cast inwards Java programming linguistic communication in addition to afterward nosotros volition come across where to occupation abstract cast in addition to interface.

Though, if you lot are preparing for Java programming interview, you lot should besides depository fiscal establishment stand upward for out the Java Programming Interview Exposed, a non bad majority peculiarly designed to laid upward for Java concepts based interview questions. It has many such questions from all of import topics e.g. oop concepts, multithreading, collections, frameworks similar Spring in addition to Hibernate, unit of measurement testing, information construction in addition to algorithm, coding, blueprint pattern in addition to modern technology scientific discipline questions similar Android, Scala, in addition to other JVM languages.

What is abstract cast in addition to interface inwards Java What is departure betwixt interface in addition to abstract cast inwards Java




Abstract cast vs Interface inwards Java

In the final section, nosotros saw what is abstract cast in addition to interface in addition to at 1 time let's come across the departure betwixt interface in addition to abstract cast inwards Java.

1) First in addition to the major departure betwixt abstract cast in addition to an interface is that an abstract cast is a cast piece the interface is an interface, agency past times extending the abstract cast you lot tin non extend unopen to other cast because Java does non back upward multiple inheritances but you lot tin implement multiple inheritance inwards Java.




2) The minute departure betwixt interface in addition to abstract cast inwards Java is that you tin non practice a non-abstract method inwards an interface, every method inwards an interface is past times default abstract, but you lot tin practice a non-abstract method inwards abstract class. Even a cast which doesn't comprise whatever abstract method tin hold upward made abstract past times using the abstract keyword.

3) The tertiary departure betwixt abstract cast vs interface inwards Java is that interface is amend suited for Type annunciation in addition to abstract cast is to a greater extent than suited for code reuse in addition to development perspective. The Effective Java has 1 detail dedicated to explaining close why you lot should hold upward using interface for type declaration. You should depository fiscal establishment stand upward for that out every bit well.

What is abstract cast in addition to interface inwards Java What is departure betwixt interface in addition to abstract cast inwards Java


4) The 4th departure betwixt abstract cast in addition to interface inwards Java is that abstract cast are slightly faster than interface because interface involves a search earlier calling any overridden method inwards Java. This is non a meaning departure inwards most of the cases but if you lot are writing a fourth dimension critical application thus you lot may non desire to acquire out whatever rock unturned.

5) Another notable departure betwixt interface in addition to abstract cast is that when you lot add together a novel method inwards existing interface it breaks all its implementation in addition to you lot demand to render an implementation inwards all clients which is non good. By using an abstract cast you lot tin render a default implementation for a novel method inwards the superclass without breaking existing clients.

Here is a prissy summary slide of highlighting fundamental differences betwixt an abstract cast in addition to interface inwards Java:
What is abstract cast in addition to interface inwards Java What is departure betwixt interface in addition to abstract cast inwards Java



That's all on the difference betwixt abstract cast in addition to interface inwards Java, I volition add together to a greater extent than differences whenever I acquire novel things. As I said, inwards the outset paragraph, after the introduction of default method inwards Java 8 (See Java 8 inwards Action) in addition to the provision that you lot tin convey both static in addition to default method within an interface, the departure betwixt abstract cast in addition to interface has choke blur. Earlier, the interface alone contains contract no implementation but at 1 time they can.

Further Learning
5 departure betwixt Hashtable in addition to HashMap inwards Java
What is Serialization inwards Java – Serializable interface
10 tough Core Java interview questions in addition to answers
Top five thread questions in addition to answers asked inwards Java Interviews
What is cast file inwards Java - How to practice Class inwards Java
10 Java Coding Interview questions in addition to Answers for Java beginners.


How To Role Coffee Enum Inwards Switch Illustration Disceptation - Exampel Tutorial

Java Enum inward Switch Case Statement
Yesterday, about 1 enquire me Can nosotros usage Java Enum inward Switch case ? Obviously, he was learning Enum too non aware that How powerful Enum inward Java is. Yes, You tin usage Enum inward Switch instance contestation inward Java similar int primitive. If yous are familiar amongst enum int pattern, where integers correspond enum values prior to Java five thence yous already knows how to  use Switch instance amongst Enum. Using Java Enum inward Switch instance is pretty straightforward, Just usage Enum reference variable inward Switch too Enum constants or instances inward CASE statement. In this Java tutorial nosotros volition encounter 1 illustration of How to usage Enum inward Switch contestation inward Java. By the means Enum is characteristic rich inward Java, Enum tin implement interface inward Java, Enum tin override method inward Java, Enum tin stimulate got constructor inward Java too Enum is total functional Type similar bird or interface. Programmers usage Enum amongst dissimilar ways. One of the best illustration of Enum inward Java is supervene upon enum int pattern too enum String pattern. You tin too use Enum to write Thread-safe Singleton inward Java.



Enum inward Switch instance - Java

In this illustration of using Enum inward Switch case, nosotros stimulate got created a Days of Week Enum which correspond all days e.g. Monday, Tuesday etc. Then nosotros acquire all Enum instances inward an array using Enum.values() method too yesteryear using advanced for loop of Java 5, nosotros loop through each of that Enum instance. By the way, yous tin too usage String inward Switch instance from Java7 onwards. Similarly, yous tin too convert Enum to String inward Java.

In the trunk of for loop, nosotros stimulate got created a switch instance contestation using Enum inward Java. Which switch on electrical current Enum instance too every CASE contestation is private Enum instance e.g. DAY.MONDAY or DAY.TUESDAY. Since yous stimulate got declared Enum inward the same bird yous tin usage their instance without calling them amongst bird lift e.g. MONDAY . Here is consummate code illustration of using Enum inward Switch instance inward Java :



 he was learning Enum too non aware that  How to usage Java Enum inward Switch Case Statement - Exampel Tutorial/**
 *
 * Java computer program to demonstrate how to usage Enum inward Switch instance statement.
 * Enum tin hold upwardly used inward switch block similar to primitive int or enum int pattern.
 * Enum tin too hold upwardly used inward CASE contestation to stimulate got appropriate activity based upon
 * Enum instance.
 *
 * @author Javin
 */

public class EnumInSwitch {

    public enum Day {

        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
    }

    public static void main(String args[]) {

        Day[] daysOfWeek = Day.values();

        for (Day today : daysOfWeek) {

            //Using Enum inward Switch instance statement

            switch (today) {
                case MONDAY:
                    System.err.println("Today is Mon larn illustration of How to usage Java Enum inward Switch");
                    break;
                case TUESDAY:
                    System.err.println("Tuesday, apply Enum inward Switch only link primitive int");
                    break;
                case WEDNESDAY:
                    System.err.println("Wednesday, I confirm Java Enum tin hold upwardly used inward Switch case");
                    break;
                case THURSDAY:
                    System.err.println("Thursday, Java Enum values() method furnish all enum inward an array");
                    break;
                case FRIDAY:
                    System.err.println("Friday, Enum tin too hold upwardly used inward instance statement");
                    break;
                case SATURDAY:
                    System.err.println("Saturday, Enum inward Java are compile fourth dimension constant");
                    break;
                case SUNDAY:
                    System.err.println("Sunday, Using Enum inward Switch is real easy");
                    break;

            }
        }
    }
}

Output:
Today is Mon larn illustration of using Java Enum inward Switch
Tuesday, apply Enum inward Switch only link primitive int
Wednesday, I confirm Java Enum tin hold upwardly used inward Switch case
Thursday, Java Enum values() method return all enum inward an array
Friday, Enum tin too hold upwardly used inward case statement
Saturday, Enum inward Java are compile fourth dimension constant
Sunday, Using Enum inward Switch is real easy


That's all on How to usage Enum inward Switch instance inward Java. Its indeed real slowly too afterwards trying it 1 fourth dimension , yous volition hold upwardly familiar amongst that. Just acquire yourself familiar amongst Enum API too about useful methods similar name(), cardinal(), values() etc, which volition assistance yous to acquire around of Java Enum apart from only using Enum inward Switch case.

Further Learning
Complete Java Masterclass
How to practise Enum from String inward Java