All Difference Between in Core Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

All Difference Between in Core Java

➢ Difference between JDK, JRE and JVM


JDK JRE JVM
The full form of JDK is The full form of JRE is Java The full form of JVM is
Java Development Kit. Runtime Environment. Java Virtual Machine.
It is a software bundle JVM executes Java
JDK is a software
which provides Java class byte code and
development kit to
libraries with necessary provides an
develop applications in
components to run Java environment for
Java.
code. executing it.
JDK is platform JRE is also platform JVM is highly platform
dependent. dependent. dependent.
It contains class libraries Software
It contains tools for
and other supporting files development tools
developing, debugging,
that JVM requires to are not included in
and monitoring java code.
execute the program. JVM.
It is the superset of JRE It is the subset of JDK. JVM is a subset of JRE.
The JDK enables
developers to create Java It is the Java platform
The JRE is the part of Java
programs that can be component that
that creates the JVM.
executed and run by the executes source code.
JRE and JVM.
JRE only contain
JDK comes with the JVM bundled in both
environment to execute
installer. software JDK and JRE.
source code.

➢ Difference between a local, instance and static


variable
Local Variable Instance Variable Static Variable

Defined within a
Defined outside a method at the Defined outside a method at the
method or a code
class level class level
block
Local Variable Instance Variable Static Variable

Is only accessible in
the method/code
Is accessible throughout the class Is accessible throughout the class
block where it is
declared

Remains in memory
Remains in memory as long as Remains in memory as long as
as long as the
the object is in memory program executes
method executes

Does not require any special Requires the static keyword to be


keyword but any access specifier specified. In addition, any access
Does not require any
(private, protected or public) can specifier (private, protected or
special keyword
be specified. Typically, private public) can be specified.
or protected is used Typically, public is used

Requires to be Is given default value based on Is given default value based on


initialized before it its data type, so does not require its data type, so does not require
is used to be initialized before it is used to be initialized before it is used.

➢ Difference between Constructors and Methods


Key Constructors Methods

Purpose Constructor is used to create and Method is used to execute


initialize an Object . certain statements.

Invocation A constructor is invoked implicitly by A method is to be invoked


the System. during program code.

Invocation A constructor is invoked when new A method is invoked when


keyword is used to create an object. it is called.

Return type A constructor can not have any return A method can have a
type. return type.
Key Constructors Methods

Object A constructor initializes an object A method can be invoked


which is not existent. only on existing object.

Name A constructor must have same name A method name can not be
as that of the class. same as class name.

Inheritance A constructor cannot be inherited by a A method is inherited by a


subclass. subclass.

➢ Difference between Static and Non-Static Methods


Key Static Methods Non-Static Methods

Access A static method can A non-static method can access both


access only static static as well as non-static members.
members and can not
access non-static
members.

Binding Static method uses Non-static method uses run time


complie time binding or binding or dynamic binding.
early binding.

Overriding A static method cannot A non-static method can be overridden


be overridden being being dynamic binding.
compile time binding.

Memory Static method occupies A non-static method may occupy more


allocation less space and memory space. Memory allocation happens
allocation happens once. when method is invoked and memory is
deallocated once method is executed
completely.
Key Static Methods Non-Static Methods

Keyword A static method is A normal method is not required to


declared using static have any special keyword.
keyword.

➢ Difference between Static and Non-Static Blocks


Static Blocks Non-Static Blocks
A static block is a block of code which A non-static block executes when the
contains code that executes at class object is created, before the
loading time. constructor.
A static keyword is prefixed before the There is no keyword prefix to make a
start of the block. block non-static block, unlike static
blocks.
All static variables can be accessed All static and non-static fields can be
freely. Any non-static fields can only be access freely.
accessed through object reference, thus
only after object construction.
All static blocks executes only once per All non-static block executes everytime
class-loader. an object of the containing class is
created.
Syntax: Syntax:
static { {
// code for static block // code for non-static block
} }

➢ Difference between Static Block and Constructor


Static Blocks Constructor
The static blocks are executed at the A Constructor will be executed
time of class loading. while creating an object in Java.
The static blocks are executed before A Constructor is called while creating an
running the main () method. object of a class.
The static blocks don't have any The name of a constructor must be
name in its prototype. always the same name as a class.
If we want any logic that needs to be A Constructor is called only once for an
executed at the time of class loading that object and it is called as many times as
logic needs to placed inside the static we can create an object. i.e The
block so that it will be executed at the constructor gets executed automatically
time of class loading. when the object is created.
Syntax: Syntax:
static { public class MyClass {
// code for static block //This is constructor
} MyClass() {
//some statements
}
}

➢ Difference between Abstraction and Encapsulation

Abstraction Encapsulation

Abstraction is a feature of OOPs Encapsulation is also a feature of OOPs. It hides


that hides the unnecessary detail the code and data into a single entity or unit
but shows the essential so that the data can be protected from the
information. outside world.

It solves an issue at Encapsulation solves an issue


the design level. at implementation level.

It focuses on the external lookout. It focuses on internal working.

It can be implemented It can be implemented by using the access


using abstract modifiers (private, public, protected).
classes and interfaces.

It is the process It is the process of containing the information.


of gaining information.

In abstraction, we use abstract We use the getters and setters methods to


classes and interfaces to hide the hide the data.
code complexities.

The objects are encapsulated that The object need not to abstract that result in
helps to perform abstraction. encapsulation.
➢Difference between Compile Time and Run time
Polymorphism

Compile Time Polymorphism Run time Polymorphism

In Compile time Polymorphism, the call In Run time Polymorphism, the call
is resolved by the compiler. is not resolved by the compiler.

It is also known as Dynamic


It is also known as Static binding, Early binding, Late binding and
binding and overloading as well. overriding as well.

Method overloading is the compile-time Method overriding is the runtime


polymorphism where more than one polymorphism having same
methods share the same name with method with same parameters or
different parameters or signature and signature, but associated in
different return type. different classes.

It is achieved by function overloading It is achieved by virtual functions


and operator overloading. and pointers.

It provides slow execution as


It provides fast execution because the compare to early binding because
method that needs to be executed is the method that needs to be
known early at the compile time. executed is known at the runtime.

Compile time polymorphism is less Run time polymorphism is more


flexible as all things execute at compile flexible as all things execute at run
time. time.

➢Difference between Abstract Class and Interface


Abstract class Interface

Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.
Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

➢Difference between this and super


this super

The current instance of the class is The current instance of the parent class is
represented by this keyword. represented by the super keyword.

In order to call the default constructor of In order to call the default constructor of
the current class, we can use this the parent class, we can use the super
keyword. keyword.

It can be referred to from a static It can't be referred to from a static


context. It means it can be invoked from context. It means it cannot be invoked
the static context. from a static context.

We can use it to access only the current We can use it to access the data
class data members and member members and member functions of the
functions. parent class.
➢Difference between this() and super()
this() super()

The this() constructor refers to the The super() constructor refers


current class object. immediate parent class object.

It is used for invoking the current class It is used for invoking parent class
method. methods.

It can be used anywhere in the It is always the first line in the child class
parameterized constructor. constructor.

It is used for invoking a super-class It is used for invoking a super-class


version of an overridden method. version of an overridden method.

➢Difference between Exception and Error


Keys Exception Error

Recovera Exception can be recovered by


ble/ using the try-catch block. An error
Error cannot be recovered.
Irrecovera cannot be recovered.
ble

Type It can be classified into two All errors in Java are unchecked.
categories i.e. checked and
unchecked.

Occurrenc It occurs at compile time or run It occurs at run time.


e time.

Package It belongs to java.lang.Exception It belongs to java.lang.Error


package. package.

Known or Only checked exceptions are Errors will not be known to the
unknown known to the compiler. compiler.

Causes It is mainly caused by the It is mostly caused by the


application itself. environment in which the
application is running.
Example SQLException, IOException, StackOverFlow,
ArrayIndexOutOfBoundException, OutOfMemoryError
NullPointerException,
ArithmeticException

➢Difference between Checked and Unchecked


Exception
Checked Exception Unchecked Exception

Checked exceptions occur at compile Unchecked exceptions occur at runtime.


time.

The compiler checks a checked The compiler does not check these types
exception. of exceptions.

These types of exceptions can be These types of exceptions cannot be a


handled at the time of compilation. catch or handle at the time of compilation,
because they get generated by the
mistakes in the program.

They are the sub-class of the exception They are runtime exceptions and hence
class. are not a part of the Exception class.

Here, the JVM needs the exception to Here, the JVM does not require the
catch and handle. exception to catch and handle.

Examples of Checked exceptions: Examples of Unchecked Exceptions:

• File Not Found Exception • No Such Element Exception


• No Such Field Exception • Undeclared Throwable Exception
• Interrupted Exception • Empty Stack Exception
• No Such Method Exception • Arithmetic Exception
• Class Not Found Exception • Null Pointer Exception
• Array Index Out of Bounds
Exception
• Security Exception
➢Difference between throw and throws keyword
throw throws

Java throw keyword is used throw an Java throws keyword is used in the
exception explicitly in the code, inside method signature to declare an
the function or the block of code. exception which might be thrown by the
function while the execution of the code.

Type of exception Using throw keyword, Using throws keyword, we can declare
we can only propagate unchecked both checked and unchecked exceptions.
exception i.e., the checked exception However, the throws keyword can be used
cannot be propagated using throw only. to propagate checked exceptions only.

The throw keyword is followed by an The throws keyword is followed by class


instance of Exception to be thrown. names of Exceptions to be thrown.

throw is used within the method. throws is used with the method
signature.

We are allowed to throw only one We can declare multiple exceptions


exception at a time i.e. we cannot throw using throws keyword that can be thrown
multiple exceptions. by the method. For example, main()
throws IOException, SQLException.

➢Difference between static and final keyword


static final
Static keyword is applicable to nested Final keyword is applicable to class,
static class, variables, methods and methods and variables.
block.
It is not compulsory to initialize the It is compulsory to initialize the final
static variable at the time of its variable at the time of its declaration.
declaration.
The static variable can be reinitialized. The final variable cannot be reinitialized.
Static methods can only access the Final methods can not be inherited.
static members of the class, and can
only be called by other static methods.
Static class's object can not be created, A final class can not be inherited by any
and it only contains static members only. class.
Static block is used to initialize the static Final keyword supports no such block.
variables.

➢Difference between catch and finally


Catch Finally
Catch block handles the error when it There is no need of exception thrown
occurs in try block. by try block.
Catch block is executed only when Finally block is always executed
the if exception is thrown by try whether exception occurs or not.
block, otherwise it is not executed.
We can use multiple catch block for Only one finally block is used for one
only one try block. try block.
We can handle multiple exceptions by It is not for exception handling.
using catch blocks.

➢Difference between Array and ArrayList


Array ArrayList

It can be single-dimensional or
multidimensional It can only be single-dimensional

For and for each generally is used for Here iterator is used to traverse
iterating over arrays riverArrayList

length keyword can give the total size() method is used to compute the
size of the array. size of ArrayList.

It is dynamic and can be increased


It is static and of fixed length or decreased in size when required.

It is faster as above we see it of fixed It is relatively slower because of its


size dynamic nature

Primitive data types can be stored Primitive data types are not directly
directly unlikely objects added unlikely arrays, they are
Array ArrayList

added indirectly with help of


autoboxing and unboxing

They can not be added here hence They can be added here hence
type unsafe makingArrayList type-safe.

Assignment operator only serves the Here a special method is used


purpose known as add() method

➢Difference between Array and Collections


Arrays Collection

Arrays are fixed in size i.e once the The collection is dynamic in size i.e
array with the specific size is declared based on requirement size could be get
then we can't alter its size afterward. altered even after its declaration.

Arrays due to fast execution consumes Collections, on the other hand, consume
more memory and has better less memory but also have low
performance. performance as compared to Arrays.

Arrays can hold the only the same type Collection, on the other hand, can hold
of data in its collection i.e only both homogeneous and heterogeneous
homogeneous data types elements are elements.
allowed in case of arrays.

Arrays can hold both object and On the other hand, collection can hold
primitive type data. only object types but not the primitive
type of data.

Arrays due to its storage and internal Collection on the other hand with
implementation better in performance. respect to performance is not
recommended to use.
➢Difference between ArrayList and LinkedList
ArrayList LinkedList

It uses a dynamic array as it’s It uses doubly linked list as it’s


internal implementation. internal implementation.

It is better in get and set It is better in adding and


operations. removing operations.

➢Difference between ArrayList and Vector


ArrayList Vector

It is not synchronized. It is synchronized.

It is not a legacy class. It is a legacy class.

It increases its size by 50% of It increases its size by doubling


the array size. the array size i.e. 100%.

Iterator interface is used to Iterator or Enumeration interface


traverse the ArrayList can be used to traverse the Vector
elements. elements.

ArrayList is much fast than Vector is slow as compared


Vector because it is non- ArrayList because it is
synchronized. synchronized

➢Difference between List and Vector


Vector List

While it has non-contiguous


It has contiguous memory. memory.

It is synchronized. While it is not synchronized.

Vector may have a default size. List does not have default size.
Vector List

In list, each element requires extra


space for the node which holds the
element, including pointers to the
In vector, each element only requires next and previous elements in the
the space for itself only. list.

Insertion at the end requires constant Insertion is cheap no matter where


time but insertion elsewhere is costly. in the list it occurs.

Vector is thread safe. List is not thread safe.

Deletion at the end of the vector


needs constant time but for the rest it Deletion is cheap no matter where
is O(n). in the list it occurs.

Random access of elements is Random access of elements is not


possible. possible.

Iterators become invalid if elements


are added to or removed from the Iterators are valid if elements are
vector. added to or removed from the list.

➢Difference between HashSet and LinkedHashSet


HashSet LinkedHashSet

It uses a Hashtable to store the elements. It uses a HashTable and doubly linked list
to store and maintain the insertion order
of the elements.

It does not provide any insertion order. It provides an insertion order; we can
We can not predict the order of predict the order of elements.
elements.

It allows only one null element. It also allows only one null element.

It requires less memory. It requires more memory than HashSet.


It provides slightly faster performance It provides low performance than HashSet
than LinkedHashSet

HashSet obj = new HashSet(); LinkedHashSet obj = new LinkedHashSet();

AbstractSet class HashSet class

➢Difference between HashSet, LinkedHashSet and


TreeSet
Property HashSet LinkedHashSet TreeSet
Underlying Hashtable Hashtable + Balanced Tree
data structure LinkedList
Insertion order Not preserved Preserved Not Applicable
Sorting order Not Applicable Not Applicable Applicable
Heterogenous Allowed Allowed Not allowed
objects
Duplicates Not allowed Not allowed Not allowed
objects
Null Allowed (only Allowed (only once) We will get
acceptance once) nullpointer
exception.

➢Difference between HashMap, LinkedHashMap,


TreeMap and HashTable
Topic Hash Linked Tree Map Hash
Map Hash Table
Map
Duplicate Not Allowed Not Allowed Not Allowed Not Allowed
Key
Ordering Unordered Maintains Maintains in Unordered
insertion Accessing
order order
Null (key Allow Allow Key not Not allowed
value) allowed but
value is
Iterator
Accessing Iterator Iterator Iterator Iterator
Elements
Thread No No No Yes
Safety

➢Difference between Comparable and Comprator


Comparable Comparator

1) Comparable provides a single sorting The Comparator provides multiple


sequence. In other words, we can sort the sorting sequences. In other words,
collection on the basis of a single element we can sort the collection on the
such as id, name, and price. basis of multiple elements such as
id, name, and price etc.

2) Comparable affects the original class, Comparator doesn't affect the


i.e., the actual class is modified. original class, i.e., the actual class is
not modified.

3) Comparable provides compareTo() Comparator provides compare()


method to sort elements. method to sort elements.

4) Comparable is present A Comparator is present in


in java.lang package. the java.util package.

5) We can sort the list elements of We can sort the list elements of
Comparable type Comparator type
by Collections.sort(List) method. by Collections.sort(List,
Comparator) method.

You might also like