Total Pageviews

Saturday, 18 August 2018

Core Java

COLLECTIONS

Importance of collections: - 
1>The main objective of collections framework is to represent group of objects as a single entity.
2>In java Collection framework provide very good architecture to store and manipulate the group of objects.
3>Collections are providing flexibility to store, retrieve, and manipulate data.

##All collection framework classes and interfaces are present in java.util package.
##The root interface of Collection framework is Collection.
##For storing and fetching data we use ArrayList but manipulation of data is slow and not efficient but if our primary objective is manipulation then Linkedlist should be used.

Collection vs Collections: - 
Collection is interface it is used to represent group of objects as a single entity.
Collections is utility class it contains methods to perform operations.

Arrays vs Collections: -
Both Arrays and Collections are used to represent group of objects as a single entity, but the differences are as shown below.

Limitations of Arrays 
1) Arrays are used to represent group of objects as a single entity.
2) Arrays are used to store homogeneous data (similar data).
3) Arrays are capable to store primitive & Object type data
4) Arrays are fixed in size, it means once we created array it is not possible to increase & decrease      the  size based on our requirement.
5) With respect to memory arrays are not recommended to use.
6) If you know size in advance arrays are recommended to use because it provide good performance.
7) Arrays does not contain underlying Data structure hence it is not supporting predefined methods.
8) While working with arrays operations (add, remove, update…) are difficult because it is not                 supporting methods.

Advantages of Collections
1) Collections are used to represent group of objects as a single entity.
2) Collections are used to store both heterogeneous data (different type) & homogeneous data.
3) Collections are capable to store only object data.
4) Collections are growable in nature, it means based on our requirement it is possible to increase &    decrease the size.
5) With respect to memory collections are recommended to use.
6) In performance point of view collections will give low performance compare to arrays.
7) Collection classes contains underlying data structure hence it supports predefined methods.
8) Here operations are become easy because collections support predefined methods.

The default capacity of the ArrayList is 10 once it reaches its maximum capacity then size is automatically increased by New capacity = (old capacity*3)/2+1 



Ques. How to get synchronized version of ArrayList?
Ans:- By default ArrayList methods are non synchronized but it is possible to get synchronized version of ArrayList by using fallowing method.
To get synchronized version of List
ArrayList al = new ArrayList(); //non- synchronized version of ArrayList
List l = Collections.synchronizedList(al); // synchronized version of ArrayList
HashSet h = new HashSet(); //non- synchronized version of HashSet
Set h1 = Collections.synchronizedSet(h); // synchronized version of HashSet
HashMap h = new HashMap(); //non- synchronized version of HashMap
Map m = Collections.synchronizedMap(h); // synchronized version of HashMap
TreeSet t = new TreeSet(); //non- synchronized version of TreeSet
SortedSet s = Collections.synchronizedSortedSet(t); // synchronized version of TreeSet
TreeMap t = new TreeMap(); //non- synchronized version of TreeMap
SortedMap s = Collections.synchronizedSortedMap(t); // synchronized version of TreeMap


Retrieving objects of collections classes:- 
We can retrieve the objects from collection classes in 3-ways
1) By using for-each loop.
2) By using get () method.
3) By using cursors(Iterator,ListIterator,Cursors).










Difference between iterator and list iterator:
> Iterator traverses in forward direction only while list iterator traverses in both forward and        backward direction.
> Iterator can be used with list , set or queue while list iterator can only be used with list

Difference between Iterator and Enumeration:
> Iterator can traverse both legacy and non legacy elements while Enumeration can traverse only      legacy elements.
> Iterator is slower than enumeration.

//---------------------------------------------------------------------------------------------------//
Comparable Vs Comparator




//----------------------------------------------------------------------------------------------------//
Anonymous Inner Class





//----------------------------------------------------------------------------------------------------//
toString() method


//-----------------------------------------------------------------------------------------------------//

Singleton Class:
A class is said to be singleton if it limits the number of objects of that class only to one.
Singleton classes are employed extensively in Networking ,jdbc etc.
//------------------------------------------------------------------------------------------------------//
Static keyword

//-------------------------------------------------------------------------------------------------------//
Association:
Association is the relationship between two different classes which are established with their objects.
Aggregation
Inheritence has IS-A relation ship while Aggregation HAS-A relationship.
Class A has instance of Class B is known as aggregation.
If a class has a entity refrence then it is known as Aggregation. It is also used for code reusability.

Composition:
In composition two entities are highly dependent on each other.
It represents part of relationship..
To be contd..

//-------------------------------------------------------------------------------------------------------//
Java Reflection API

Java Reflection is a process of examining or modifying the run time behavior of a class at run time.

Security issues since it can access private data too.
Performance issue since it involves process like scanning of class path.




//--------------------------------------------------------------------------------------------------------//
Generics in Java
Generics is the facility of generic programming in java.Its benifits are type safety ,type casting not required and since its checked at compile time so problem will not happen at run time. It was introduced in java 1.5.
Example:
****Before generics we were using arraylist like this:
List list = new ArrayList();
list.add("hello");
String s = (String)list.get(0); //typecasting
 ****After generics we dont need to type cast the object
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);


Generic class:
A class that can refer to any type is known as generic class

Generic Method:
A generic method can accept any type of argument.

Wild Card in java generics:
The ? mark is known as wild card in generic programming.It means any type.
refer: https://www.javatpoint.com/generics-in-java
//--------------------------------------------------------------------------------------------------------//
Lamda Expression:-
Lambda expression provides clear and consise way to represent one method interface using an expression. It was introduced in Java 8

FYI: Lambda expressions only works with functional interface(functional interface means , interface with just one abstract method in it.)
There are different types of interfaces like functional interface,nested interface,marker interface(i.e. empty interface)

//--------------------------------------------------------------------------------------------------------//
Java Enum
Enum in java represents data type that contains fixed set of constants.

//--------------------------------------------------------------------------------------------------------//
JDK, JRE & JVM
> To Develop and run java application we need to have JDK.
> Just to run java application we need to have JRE.
> In JRE , JVM is responsible for running our program line by line. JVM is a interpretor.

JDK = JRE + Development Tools
JRE = JVM + Library Classes

First compiler converts source file( which contains our classes) into byte code then JVM executes this byte code line by line.

Polymorphism:-
The process of performing tasks in different ways is known as polymorphism.
There are two types of polymorphism:
1) Compile time polymorphism / static binding / early binding
Example :- method overloading
2) Runtime polymorphism /dynamic binding /late binding.
Example :- method overriding
There are three types of overloading in Java
--Method overloading
     #class contains more than one method with same name but different number of arguments or argument type
--Constructor overloading
     #constructor with different number of argument or argument data type
--Operator overloading
     #Java doesnot support operator overloading but one overloaded operator is present implicitly i.e. '+'
10+"gaurav" = 10gaurav
10+"gaurav"+10+20 = 10gaurav1020
10+"gaurav"+(10+20)=10gaurav30
 

 
Rules for overriding in Java:-
1> While overriding overridden method signature and overriding method signature must be same.
2> While overriding overridden method return type and overriding method return type must be same.
3> It is possible to change return type of method by using covariant return type.
4> It is not possible to override final methods in java.
   
   Just for Info.
   # Final class variables are not a final but final class methods are final.
   
5> Static method overriding is not possible.
6> It is not possible to override private methods.Private methods are not visible in child classes.
7> Reducing permission while overriding is not possible in java.Permission can either be at same level or in increasing order.
   
   example:
   
   Class Parent{
void m1(){       // here it is having default permission
}
   }
   
   Class child extends Parent{
  public void m1(){     // here we have increased permission. If instead of public we gave private then it would have thrown compile time error
  
  }
   }
   
   Just for Info.
   Access modifire perfmission:
   
   Public       : variable , method , class     : Any package can access
   Protected  : variable , method                : With in package and outside package by child class only
   Private      : variable , method                : With in class only
   Default     : variable , method , class     : With in package 
   
Abstraction: 
--The process of highlighting the set of services and hiding the implementation is known as Abstraction.
--We achive abstration by using abstract classes (0-100%) and interfaces(100%);
--We can declare class as abstract even if it doesnot have abstract methods.
--We can not create object of abstract class.
e.g. 
abstract Class A{         // abstract class
abstract void m1();   // abstract method
void m2(){            // non abstract method
}
}
Ques: How to prevent object creation of class?
Ans:  Declare the class as abstract class to prevent object creation.

Ques: How to prevent inheritence?
Ans: Declare the class as final.

Ques: How to prevent overriding?
Ans: Declare the method as final.

--Inside abstract class we can declare constructors
--Interface methods are by default public.



Encapsulation:-
The process of binding code and data togeather as single unit is known as encapsulation.

Just for info.
-- Bean class contains data,getters and setters method
-- A class is said to be tightly encapsulated if and only if, all the data members(variables) of that class is declared as private.

Ques: System.out.println();
Ans:  System  :   Class present in java.lang package
      out     :   Static variable present in System class of type print stream
  println :   method present in print stream class
  
  
Interfaces:-
Interfaces are extension of abstract classes and contains abstract methods.

-- By default interface methods are public and abstract.
-- If we want to declare only few methods of interface then we will have to declare that class as abstract in which we are implementing interface.
-- In java one class can only extend one class at a time but interface can extend multiple interfaces at a time

Nested Interfaces:

   interface It1(){
interface It2(){
void m1();
}
   }
   
   Class Test implements It1.It2{
public void m1(){
syso("");
}
   }
   
-- It is possible to declare interface inside class also.
-- Interface is by default abstract
-- Interface methods are by default public and abstract
-- Interface variables are by default public static final.

Scope of variables in Java:
Variables are of three types in Java
1>Instance variable
2>Local Varibale
3>Argument Variables

Instance Variables: Instance variables are those which belong to class itself and not in any method or constructor of class.
  Scope: Scope of these variables are determined by the access specifier that is applied to these variables.
  Lifetime: Life time of these variables are same as the life time of of object to which it belongs to.
  
Argument Variables: These are variables which are defined in the header of method or constructor itself.
  Scope: Scope is limited to method or constructor in which they are defined.
  Lifetime: Life time is limited to time in which method or constructor keeps executing.
  
Local Variables: Local variables are those which are defined inside body of method or constructor.
  Scope and lifetime is limited to method itself.
  
  [FYI: Access specifier can only be applied to instance variable not to local or argument variable, if you will try to apply access specifier to local or argument variable
        compiler will throw error stating only final is permitted]
  
  
  
Just for info.
Objects once created do not exist forever.They are destroyed by garbage collector when there are no more refrence to that object.

//--------------------------------------------------------------------------------------------------//

Coupling in Java:

There are two types of coupling in java.
1> Tight Coupling
2> Loose Coupling

Tight Coupling
Tight Couple means classes and objects are dependent on each other.


Loose Coupling
Loose Coupling means classes and objects have minimal dependency on each other.


String Vs String Buffer Vs String Builder
  • Objects of String are immutable, and objects of StringBuffer and StringBuilder are mutable.
  • StringBuffer and StringBuilder are similar, but StringBuilder is faster and preferred over StringBuffer for single threaded program. If thread safety is needed, then StringBuffer is used.
  • The objects created as strings are stored in constant string pool while the objects created using buffer/builder are stored in heap.

Stack vs Heap
To be cond..


Method Hiding in Java:
Static method are bounded with class while instance method are bounded with object.
In Java it is possible to override only instance methods not static methods.

When we try to override static method concept of method hiding comes in picture.

Method hiding means :- Subclass has defined a method with same signature as superclass, and method of superclass is hidden by subclass. It means, the version of method that is executed will not be determined by the object that is used to invoke it.In fact it will be determined by the type of reference variable used to invoke the method

Example:



Ques: Why cant static method be overridden?
Ans: Because static methods are resolved statically i.e. at compile time based on the class they are called on, not dynamically as in the case with instance methods which are resolved polymorphically based on run type of object.

FYI: Static methods should always be accessed in static way i.e. name of class followed by name of method.




Ques: Different Ways of creating object in java.
Ans:



Ques: Difference between global and static global variable
Ans: 


Ques: Create your own ArrayList
Ans:







No comments:

Post a Comment