Showing posts with label java faqs. Show all posts
Showing posts with label java faqs. Show all posts

Saturday, June 13, 2020

Differences between JDK, JRE and JVM


In the Java programming language, all source code is first written in plain text files ending with the .java extension. You can write it in any notepad or text editor or IDE. Those source files are then compiled into .class files by the javac compiler.

A .class file does not contain code that is native to your processor,  it instead contains byte codes , the machine language of the Java Virtual Machine (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.

To understand the difference between JDK, JRE AND JVM please consider below diagram:
                  JDK = JRE +DEVELOPMENT TOOLS
                  JRE = JVM + LIBRARY CLASSES

JAVA DEVELOPMENT KIT (JDK):

The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as, an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) and other tools needed in Java development.

JDK is an acronym for Java Development Kit.  It physically exists. It contains JRE + development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
 
Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers, e.g. a javac compiler. The Java Development Kit is provided free of charge either by Oracle Corporation directly, or by the OpenJDK open source project, which is governed by Oracle.

Java Development Kit (in short JDK) is Kit which provides the environment to develop and execute(run) the Java program. JDK is a kit(or package) which includes two things
Development Tools(to provide an environment to develop your java programs)
JRE (to execute your java program).
Note : JDK is only used by Java Developers.

Java Runtime Environment (JRE):

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

Java Runtime Environment (JRE) is a software package that contains what is required to run a Java program. It includes a Java Virtual Machine implementation together with an implementation of the Java Class Library. The Oracle Corporation, which owns the Java trademark, distributes a Java Runtime environment with their Java Virtual Machine called HotSpot.

 JRE is an installation package which provides environment to only run(not develop) the java program(or application)onto your machine. JRE is only used by them who only wants to run the Java Programs i.e. end users of your system.

JRE consists of the following components:
  • Deployment technologies, including deployment, Java Web Start and Java Plug-in.
  • User interface toolkits, including Abstract Window Toolkit (AWT), Swing, Java 2D, Accessibility, Image I/O, Print Service, Sound, drag and drop (DnD) and input methods.
  • Integration libraries, including Interface Definition Language (IDL), Java Database Connectivity (JDBC), Java Naming and Directory Interface (JNDI), Remote Method Invocation (RMI), Remote Method Invocation Over Internet Inter-Orb Protocol (RMI-IIOP) and scripting.
  • Other base libraries, including international support, input/output (I/O), extension mechanism, Beans, Java Management Extensions (JMX), Java Native Interface (JNI), Math, Networking, Override Mechanism, Security, Serialization and Java for XML Processing (XML JAXP).
  • Lang and util base libraries, including lang and util, management, versioning, zip, instrument, reflection, Collections, Concurrency Utilities, Java Archive (JAR), Logging, Preferences API, Ref Objects and Regular Expressions.
  • Java Virtual Machine (JVM), including Java HotSpot Client and Server Virtual Machines.

Java virtual machine (JVM):

A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a Java program. It is called a virtual machine because it doesn't physically exist. It is a specification that provides a runtime environment in which Java byte code can be executed. It can also run those programs which are written in other languages and compiled to Java byte code.

A JVM (Java Virtual Machine) is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris™ Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java SE HotSpot at a Glance, perform additional steps at runtime to give your application a performance boost. This includes various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent because the configuration of each OS is different from each other. However, Java is platform independent. There are three notions of the JVM: specification, implementation, and instance.The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

Java Virtual machine(JVM) is a very important part of both JDK and JRE because it is contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing the java program line by line hence it is also known as interpreter.


 The specification is a document that formally describes what is required of a JVM implementation. Having a single specification ensures all implementations are interoperable. A JVM implementation is a computer program that meets the requirements of the JVM specification. An instance of a JVM is an implementation running in a process that executes a computer program compiled into Java bytecode.

The JVM performs the following main tasks:
  • Loads code (Class Loader)
  • Verifies code (Byte Code Verifier)
  • Executes code (Interpreter)
  • Provides runtime environment (Run Time Environment)

Class Loader: The Class Loader loads all necessary classes needed for the execution of a program. It provides security by separating the namespaces of the local file system from that imported through the network. These files are loaded either from a hard disk, a network or from other sources.

Byte Code Verifier: The JVM puts the code through the Byte Code Verifier that checks the format and checks for an illegal code. Illegal code, for example, is code that violates access rights on objects or violates the implementation of pointers.

Intrepreter: At runtime the Byte Code is loaded, checked and run by the interpreter. The interpreter has the following two functions:
  • Execute the Byte Code
  • Make appropriate calls to the underlying hardware

What are the some of the best practices related to collections ?


While using Collections in Java programming the java developer needs to understand and implement the best practices to improve the code quality and improve the performance of the application. That will enhance the stability , performance and maintainability of the java applications.

  • Use ArrayLists , Hashmaps etc instead of Vector and Hashtable etc, where possible to avoid any synchronization overhead. Even better is to use Arrays where possible if you know the size in advance. 
  • If multiple threads concurrently access a collection and at least one of the threads either adds or deletes an entry into the collection, then the collection must be externally synchronized instead of using default synchronized classes like Vector and Hashtable. This can be achieved by using the below piece of code :
                Map myMap = Collections.synchronizedMap(myMap); 

                List myList = Collections.synchronizedList(myList);

  • Set the initial capacity appropriately ( e.g. ArrayList, HashMap etc) . This is because Collection classes like ArrayList, HashMap etc must grow periodically to accommodate new elements. But if you have a very large array, and you know the size in advance then you can speed things up by setting up the initial size appropriately.
For Example: 
  • HashMaps/Hashtables need to be created with sufficiently large capacity to minimize rehashing (which happens every time the table grows). HashMap has two parameters initial capacity and load factor that affect its performance and space requirements. 
  • Heigher load factor values (default load factor of 0.75 provides a good trade off between preformance and space) will reduce the space cost but will increase the lookup cost myMap.get(...) and myMap.put(...) methods. When the number of entries in the HashMap exceeds the current capacity * loadfactor then the capacity of the HashMap is roughly doubled by calling the rehash function. It is also very important not to set the initial capacity too high ot load factor too low if iteration performance or reduction in space is imporatant.
  • Program in terms of Interface not implementation: For example you might decide a LinkedList is the best choice for some application, but then later came to know that the ArrayList might be a better choice for better performance reason. In that scenario you need to code as below :
Code : List list = new ArrayList(100); //Application in terms of interface & set the initial capacity.

instead of as below :
 ArrayList list = new ArrayList();

Avoid storing unrelated or different types of objets into same collection possibly : This is analogous to storing items in pigeonholes without any labeling. To store items use value objects or data objects (as appose to storing every attribute in an ArrayList or HashMap ). Provide wrapper classes around your collection API classes like ArrayList, HashMap etc . Also do applicable consider using composite design pattern, where an object may represent a single object or a collection of objects.

Tuesday, June 9, 2020

Differences between HashMap and Hashtable


Both HashMap and Hashtable classes are Map interface implementations . HashMap and Hashtable classes have below defferences based on their functionality and behavior.

HashMapHashtable
HashMap is not a legacy classHashtable is a legacy class
HashMap is not synchronized. If required HashMap can be synchronized as below:
Map m = Collections.synchronizeMap(hashMap);
Hashtable is internally synchronized and can't be unsynchronized. It is thread-safe and can be shared with many threads.
HashMap can contain one null key and multiple null values.Hashtable cannot contain any null key or null value.
HashMap is not thread-safe, so it is useful for non-threaded applications.Hashtable is thread-safe, and it can be shared between various threads.
HashMap inherits the AbstractMap classHashtable inherits the Dictionary class.
Iterator in the HashMap is fail-safeEnumerator for the Hashtable is not and throw ConcurrentModificationException
HashMap is fastHashtable is slow
HashMap inherits AbstractMap class.Hashtable inherits Dictionary class.
HashMap is traversed by Iterator.Hashtable is traversed by Enumerator and Iterator.

Monday, June 8, 2020

Differences between Comparable and Comparator


Both Comparable and Comparator or interfaces used to sort Collection elements. Both have one ,one method compareTo() and compare() to provide sorting and these are very useful in case of sorting .

ComparableComparator
Comparable interface is found in java.lang package.Comparator interface is present in java.util package.
It provides one method named compareTo()It provides one method named compare()
Comparable provides only one sort of sequence.Comparator provides multiple sorts of sequences
If we implement the Comparable interface, the actual class is modified.The actual class is not changed.
Comparable interface compares “this” reference with the object specifiedComparator in Java compares two different class objects provided.
Comparable interface is used to sort the objects with natural ordering.Comparator in Java is used to sort attributes of different objects.

Differences between Collection and Collections



Collection : Collection is an interface which can be used to represent a group individual objects a single entity.

Collections: Collections is an utility class present in java.util package to define several utility methods ( like sorting ,searching like ) for Collection objects.

CollectionCollections
Collection is an interface which can be used to represent a group individual objects a single entity.Collections is an utility class present in java.util package to define several utility methods ( like sorting ,searching like ) for Collection objects.
The Collection interface provides the standard functionality of data structure to List, Set, and Queue.Collections class is to provide utilities like sort,search and synchronize the collection elements.
Collection interface provides the methods that can be used for data structureCollections class provides the static methods which can be used for various operation on a collection classes

Friday, June 5, 2020

Differences between Iterator and Enumeration


What are the differences between Iterator and Enumeration? Core Java Collections Interview Question


ANS) Both Iterator and Enumeration are used to iterate the elements from the Collections.Below are the some of the differences between iterator and enumeration :

IteratorEnumeration
The Iterator is slower than Enumeration.Enumeration is faster than Iterator.
The Iterator is fail-fast.Enumeration is not fail-fast.
It throws ConcurrentModificationException if a Collection is modified while iterating other than its own remove() method.It does not throw ConcurrentModificationException if Collection is modified during the traversal.
The Iterator can traverse legacy and non-legacy elements.Enumeration can traverse only legacy elements.
Iterator is not a legacy interface. Iterator can be used for the traversal of HashMap, LinkedList, ArrayList, HashSet, TreeMap, TreeSet .Enumeration is a legacy interface which is used for traversing Vector, Hashtable.
Iterator has hasNext(),next() and remove() methodsEnumeration has hasMoreElements() and nextElement() methods
The Iterator can perform remove operation while traversing the collection.The Enumeration can perform only traverse operation on the collection.


There are couple of similarities between Iterator and Enumeration in Java

  • Interface :  Both Iterator and Enumeration are interfaces.
  • Package :  Both Iterator and Enumeration are present in java.util package. 
What does Fail-fast Mean ?

The Iterator in java which immediately throws ConcurrentmodificationException, if any structural modification occurs in, is called as a Fail-fast iterator. Fail-fast iterator does not require any extra space in memory.