Java Interview Preparation (conceptual)

 All Concepts sumerized ....
-------------------------------------------------------------

***Java is partially Object-oriented as it has primitive types.
(Primitive i.e. int, float are not the objects, to convert them to use as Object, we use wrapper class)

***Java is platform-independent but JVM dependent. And JVM is platform dependent because for Linux there is a different JVM whereas for windows it's different.

_-_____-----___--___--____---
Oops Concept 
_-_____-----___--___--____---

abstraction
encapsulation
inheritance
polymorphism

Inheritance :


Real-World Example :

Children have some of the qualities of their parents and grandparents or their ancestors.

Java Example:

There is a method in the parent class and you want the same method to create in a child class. Why create a new one if it already exists. As a child, you can inherit the method.

There are a few variables in a class and you need them .So why to create new variables. We can extend that class (means we can be a child of that class so that the qualities of that class such as variables, methods, and all available in the child class).


Encapsulation :

Real-World Example :

Have you ever seen the tablets you take while you are ill? The contain of the tablet is encapsulated with a cover, which is a thin plastic or something. i.e. wrapped.


Java Example :
Wrapping of data is called Encapsulation.The example is that the use of getter and setter i.e. get() method and set() method to set a value to a variable that is private.

E.g. there is a variable in the class i.e. salary. So that salary if made public, will be accessible for everyone which is not secure. So I made that variable salary as private and now told people to set their salary by using a method only i.e. setSalary() because as I have made the variable salary private, they can't simply access that and now my variable is secure.

Same if someone wants to get his salary detail, as I have made salary private, he or she can't access. I will give him a method so that he can access his salary only by the method getSalary().



PolyMorphism :

Real-World Example :

Poly means more than one and morph means form. Combining means, more than one form.A man is a father at home, a teacher at the profession.So it's his different roles or forms in different places.

Java Example :


There are two types of polymorphism in java.

!. Compile Time Polymorphism /Static Polymorphism
   (OverLoading)
2. Run Time Polymorphism / Dynamic Polymorphism
   (Overriding) 


!. Compile Time Polymorphism /Static Polymorphism
   (OverLoading)



Here the method name will be same but the number of parameters will must be different.

Ex: Method for Adding values ...

int add(int, int)
int add(int , float)
float add (float,int)
float add(int,int,int)

All four are overloading methods.



2. Run Time Polymorphism / Dynamic Polymorphism
   (Overriding) :


Overriding is possible only in inheritance. If we have already existed a method in the parent class we can just inherit that class as parents and override that method. Now we can change the body only and set it according to our requirement.


Abstraction :

Real-World Example :

All we are doing ATM transactions such as cash withdrawals and money transfer but we are not able to know the internal mechanism or details of the ATM. Abstraction provides security to data from unauthorized methods. Only provide essential information about the data to the outside world, hiding the background details and information.

Java Example :

Abstract Class 
Abstract Method

Abstract Method :-

What is the use?
(Real World + technical  Example)

We have to design a prototype for any bike , i.e. a universal, not for specific.

So we created a class bike and put a method bikeColor() which contains nothing inside it.A method with no body. We wish people to inherit us and override this method and put some content inside.

Now honda inherit our class and override the method bikeColor()  and set the color as black.

Now the method with no body as discussed in bike class is called an abstract method.

Honda class override that method and gave the body to that method.


So the class which contains the abstract method is named as abstract class and used an abstract keyword in both the class and method.

If a normal class inherits an abstract class and doesn't give body to the abstract method, now this normal class will must be declared as abstract class.because if you inherit an abstract class ,then the abstract method in parent class will come to you as inheritance property and now if you have abstract method and you are not giving body to it , you will have abstract method in your class and so your class have to be declared abstract.


Abstract class :
 0- 100% abstraction
 in an abstract class, there will be no abstract method or all abstract method or some abstract   methods. Means abstract class can have an abstract and non-abstract method.

Interface :
 100% abstraction
 In an interface, all methods must be abstract. 
 (Since Java 8, it can have default and static methods also.)




Abstract classInterface
1) Abstract class can have abstract and non-abstract methods.Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
2) Abstract class doesn't support multiple inheritance.Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non-static variables.Interface has only static and final variables.
4) Abstract class can provide the implementation of interface.Interface can't provide the implementation of abstract class.
5) The abstract keyword is used to declare abstract class.The interface keyword is used to declare interface.
6) An abstract class can extend another Java class and implement multiple Java interfaces.An interface can extend another Java interface only.
7) An abstract class can be extended using keyword "extends".An interface can be implemented using keyword "implements".
8) A Java abstract class can have class members like private, protected, etc.Members of a Java interface are public by default.
9)Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}


Source : Javatpoint


-____--_---__-----____

UseFul Terms and topics :

__--___---________---_____




Super
This
Dynamic Method Dispatch
Singleton
Serialization And Deserialization
Final 

Serialization:

Writing Object to file 

Deserialization :

Reverse of serialization 

--__--__--__----________

Exception Handling Concept In Java
--____--___--_____-_____------

Throwable
Exception
Error
throw
throws
try
catch
finally



throw :
explicitly throw an exception

Throws :
Let the exception to handle by JVM
public class AddNumber throws NumberFormatException

--_---_______---__---_____---__

Collection Framework In Java

--_---______--_____-___-________


Hierarchy :




Source: Google search 








 
Iterator :
can Traverse forward direction only.

List Iterator :
can Traverse both the forward and backward direction.


List :- 
**can have Duplicate Element 
**can have Null
**Package : java.util
**Inherits : Collection Interface
**List-Iterator
**Implementation : Array List , Linked list , stack , vector

Important methods :

int size()   , 
void add(int index, E element)  , 
boolean add(E,e) , 
boolean addAll(int index, Collection<? extends E> c) ,          
void clear() ,    
int hashcode()        ,
E get(int index)       
boolean isEmpty()     ,
boolean contains(Object o)            ,
boolean containsAll(Collection<?> c)
int indexOf(Object o)    ,  
 E remove(int index)  , 
boolean removeAll(Collection<?> c)   ,
void replaceAll(UnaryOperator<E> operator)     , 
void retainAll(Collection<?> c) ,  
E set(int index, E element)   ,
void sort(Comparator<? super E> c) ,       
Spliterator<E> spliterator()  ,
List<E> subList(int fromIndex, int toIndex)


Source : List In Java



Convert List to Array :
use toArray()
 String[] array = AnyList.toArray(new String[ AnyList.size() ]);  
Here AnyList is an arraylist and array is an array of type string.  












--__--______--___---__

Set Interface

___--_______-------____-_



** No Duplicate Element 



Methods :

Sr.No.Method & Description
1

add( )

Adds an object to the collection.

2

clear( )

Removes all objects from the collection.

3

contains( )

Returns true if a specified object is an element within the collection.

4

isEmpty( )

Returns true if the collection has no elements.

5

iterator( )

Returns an Iterator object for the collection, which may be used to retrieve an object.

6

remove( )

Removes a specified object from the collection.

7

size( )

Returns the number of elements in the collection.

 
Set :

Hash SEt :

no Order
Not synchronised
No duplicate
TRee SEt :

sorted in ascending order by default
not Synchronised
no duplicate

Linked Hash SEt :



TreeSEt implements shorted set :

*** So elements in tree set are sorted by default.











Map :



*Key Value Pair 
*search, update or delete elements on the basis of a key.

*No duplicate keys 
*Duplicate Values Allowed

*Hash Map and Linked Hash Map allow Null keys and values 
* TreeMap not allow any null key and value.

*A map can't be traversed. We have to use set like keySet() or entrySet() to traverse a map.

*Iterator also can be used.




Difference :
------------------------

Hash MAp :

*No order Maintain


TreeMap:

*Maintain Ascending Order 
(Implements Map and SortedMap so sorted)


LinkedHashMAp :

*Maintains Insertion Order
*Implementation of Map
*Inherits Hash Map


MethodDescription
V put(Object key, Object value)It is used to insert an entry in the map.
void putAll(Map map)It is used to insert the specified map in the map.
V putIfAbsent(K key, V value)It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key)It is used to delete an entry for the specified key.
boolean remove(Object key, Object value)It removes the specified values with the associated specified keys from the map.
Set keySet()It returns the Set view containing all the keys.
Set<Map.Entry<K,V>> entrySet()It returns the Set view containing all the keys and values.
void clear()It is used to reset the map.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value)This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key)This method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o)It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? super V> action)It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key)This method returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue)It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode()It returns the hash code value for the Map
boolean isEmpty()This method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value)It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue)It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection values()It returns a collection view of the values contained in the map.
int size()This method returns the number of entries in the map.


Source : JavaTpoint



Traverse A Map Ways :
-----------------------------------------

for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Note :

**

Do you want to iterate the entries (key+value) or only keys or only values? That's why you obtain the specific collection and obtain an iterator.

Since keys/entries are unique (no duplicate elements present), you obtain a set through entrySet() and keySet(). And since values can have duplicates, you obtain the collection through values() and then get an iterator from these.



**

It depends on what value the programmer is seeking to iterate. Either it's just keys or values or both. based on that, we have three different objects that can be iterated. Example: mapObject.keySet().iterator(); or mapObject.values().iterator(); or mapObject.entrySet().iterator(). The only thing to keep in mind is that, when we iterate over just values() collection, we won't get respective keys by any means.



Collections And Collection
---------------------------

--> Collections is a class in java.util package
--> Collection is an interface

***java.util.Collections.sort() method is present in java.util.Collections class.  

***It is used to sort the elements present in the specified list of Collection in ascending order.

***It works similar to java.util.Arrays.sort() method but it is better then as it can sort the elements of Array as well as linked list, queue, and many more present in it.


Important Topics 
-----------------------------------------------
Access specifiers
scope

Wrapper class
primitives

 
Super
This
Dynamic Method Dispatch
Singleton
Serialization And Deserialization
Final
threadsafe
multithreading


Throwable
Exception
Error
throw
throws
try
catch
finally
 
Collection
Collections
Iterable interface
Collection Interface
List
Queue
Set
Map
Array List
Dequeue
HashSet
TreeSet
SortedSet
HashMap
TreeMap
ShortedMap
Linked hashmap
Linked hashset
Linked List
vector
stack
Methods in list map and set (in collection framework)

Comments

Popular posts from this blog

Git Commands With Output Log

Java 8 Function Interface