CodeByAkram

Bubble Sort

Bubble Sort

The bubble sort makes multiple passes through a list and sometimes referred to as sinking sort. It is a simple sorting algorithm that compare the adjacent elements and swap their position if they are nor in intended order. Each pass through the list places the next largest value in its proper place. In essence, each item “bubbles” up to the location where it belongs.

So now lets talk about How Bubble sort works?
Lets take an list as shown below

Bubble Sort


As Shown above, Starting from the first element, two adjacent elements are compared. If the former element is greater than the latter one, they are swapped. This process goes on for all consecutive-element pairs until the last unsorted element.

And again it will follow the same recursive method till the complete list is sorted.
class BubbleSort{

  public void bubbleSort(int array[]){

    int size = array.length;

    for (int i = 0; i < size-1; i++){

      for (int j = 0; j < size-i-1; j++){

        if (array[j] > array[j+1]){

          int temp = array[j];

          array[j] = array[j+1];

          array[j+1] = temp;

        }

      }

    }

  }

  Public void printArray(int array[]){

    int size = array.length;

    for(int i=0; i < size; ++i)

      System.out.print(array[i]+" ");

      System.out.println();

  }

  public static void main(String args[]){

  int[] data = {-2, 45, 0, 11, -9};

  BubbleSort bs = new BubbleSort();

  bs.bubbleSort(data);

  System.out.println("Sorted Array in Ascending Order:");

  bs.printArray(data);

  }

}

Complexity
Now lets talk about the complexity of bubble sort.
As Bubble sort is the simplest sorting algorithm and in above java code we have implemented two foor loops, So the complexity of of this algorithm is O(n*n) = O(n2 ). This is the worst case complexity.

Where we can use bubble sort?
1.      Where the complexity of code does not matters
Where a sort code is refer.

Factorial of number in Java


Factorial of number in Java.

Factorial of number is product of a number and the following number below it.
For Example: 
Factorial of 6

6! =6 * 5 * 4 * 3 * 2 * 1 = 720.

Factorial of 5 
5! = 5 * 4 * 3 * 2 * 1 = 120.

Note: The value of 0! is 1


Algorithm

Now Lets talk about the algorithm for printing Factorial of a Number in java.

There ae 3 ways of finding Factorial of number,


  1. Recursive Implementation
  2. Iterative Implementation
  3. Using BigInteger for Large values.
Check Recursive Implementation Program flow below.



Java Program to Print Factorial of a number using Recursion.

package codebyakram;
 
import java.math.BigInteger;
 
public class FindFactorialOfNumber {
 
 public static void main(String[] args) {
  System.out.println(factRecursive(5));
  System.out.println(factIterative(5));
  System.out.println(factorialForLargeNumbers(5));
 }
 
 //Recursive Implementation
 private static int factRecursive(int num){
  if(num < 0){
   return -1;
  }
 
  if(num == 1 || num == 0){
   return 1;
  }
  num = num * factRecursive(num-1);
  return num; 
 }
 
 //Iterative Implementation
 private static int factIterative(int num){
  if(num < 0){
   return -1;
  }
 
  int fact = 1;
  for (int i = 1; i <= num; i++) {
   fact *= i;
  }
  return fact;
 }
 
 //Using BigInteger for Large values
 public static String factorialForLargeNumbers(int num) {
  if(num < 0){
   return "-1";
  }
   
  BigInteger fact = new BigInteger("1");
   
  for (int i = 1; i <= num; i++) {
   fact = fact.multiply(new BigInteger(String.valueOf(i)));
  }
  return fact.toString();
 }
 
}

Method overloading example program in Java


What is method overloading?

If a class have multiple methods with same name but with different parameters list, it is known as Method Overloading.
Parameters lists should differ in either,
  1. Number of parameters.
  2. Data type of parameters.
  3. Sequence of data type of parameters. 

Example:


class ArithmeticOperations{  
 public void add(int num1,int num2){
  System.out.println(num1 + num2);
 }  
  
 public int add(int num1,int num2, int num3){
  int result = num1 + num2 + num3;
  return result;
 }
   
 public static void main(String args[]){  
  ArithmeticOperations obj = new ArithmeticOperations();    
  obj.add(1,2);
  int result = obj.add(1,2,3);
  System.out.println(result);
 }
}
What is benefit of method Overloading?

Method overloading increases the readability of the program.
Example of Java API using method Overloading?

1.  "valueOf" method of String class is overloaded in Java. It returns String representation
of variable passed in it.

2.  "substring" method of String class is overloaded in Java.

3.  "println" method of PrintStream class is overloaded.

Note: Method overloading is one of the way through which java supports polymorphism. Polymorphism achieved using method overloading is known as Compile time/Static polymorphism because which method will be invoked is decided at compile time.

Example of Real time use of method Overloading?

There is a Organization where many Employee works and we need to design a system for it. In design, for getting Employee we would have a EmployeeModel something like this, 
class Employee{
 private int id;
 private String name;
 
 //Getter & Setters
}
 
class EmployeeModel{  
 
 //Get Employee by name and dob.
 public Employee getEmployee(String name, Date dob){
  //Logic for fetching Employee emp
  return emp;
 }
 
 //Get Employee by name
 public List getEmployee(String name){
  //Logic for fetching list of Employee emp
  return listEmp;
 }
 
 //Get Employee by id  
 public Employee getEmployee(int employeeId){
  //Logic for fetching Employee emp
  return emp;
 }
}

How is ambiguous overloaded method call resolved in java?

Question 1. What is the output of below program?  
public class OverloadedMethod{
 public void test(String str) {
  System.out.println("String");
 }
  
 public void test(Object obj) {
  System.out.println("Object");
 }
  
 public static void main(String[] args) {
  OverloadedMethod obj = new OverloadedMethod();
  obj.test(null);
 }
}
Output: String

On what basis Compiler decides which method to invoke?
If more than one method is both accessible and applicable to a method invocation then
Java compiler uses the set of rules that the most specific method is chosen for invocation.

In our case above, call to test(null) is suitable for both the test method declared, So in this case most specific method is chosen for invocation.

Compiler check the class hierarchy of method parameter and whichever class is least general one that is the class which is encounter first in bottom up hierarchy, that method is invoked.

Compiler will found String class as the most general class in bottom up inheritance hierarchy, that is why test(String) method is invoked

Question 2. What is the output of below program? 


public class OverloadedMethod{
 public void test(String str) {
  System.out.println("String");
 }
  
 public void test(StringBuffer obj) {
  System.out.println("Object");
 }
  
 public static void main(String[] args) {
  OverloadedMethod obj = new OverloadedMethod();
  obj.test(null);
 }
}
Output: Compile time error:               
     The method test(String) is ambiguous for the type OverloadedMethod
Why compiler doesn't able to resolve overloaded method call this time?

StringBuffer and String class are both at same level in Object hierarchy, So in this case Compiler will not able to resolve which method to invoke and it gives Compile time error.
Let's see one more example and we will be get this better.


Question 3. What is the output of below program?  


class A{}
 
class B extends A{}
 
class C extends B{}
 
class OverloadedMethod{
 public void test(B obj) {
  System.out.println("B");
 }
  
 public void test(C obj) {
  System.out.println("C");
 }
  
 public static void main(String[] args) {
  OverloadedMethod obj = new OverloadedMethod();
  obj.test(null);
 }
}
Output: C

Output is "C" because test(null) method call maps to method which contains parameter as class which is lowest in class hierarchy.
Note: Rules that applies for evaluating method call in overloading.

  1. Widening wins over boxing eg. test(10) will call test(long) instead of test(Integer) if both are available.
  2. Widening wins over var-args eg test(byte,byte) will call test(int,int) instead of test(byte...x) method.
  3. Boxing beats var-args eg test(byte,byte) will call test(Byte,Byte) instead of test(byte...x) method.
  4. Widening of reference variable depends on inheritance tree(so, Integer cannot be widened to Long. But, Integer widened to Number because they are in same inheritance hierarchy).
  5. You cannot widen and then box. Eg. test(int) cannot call test(Long) since to call test(Long) the compiler need to convert int to Integer then Integer to Long which is not possible.
  6. You can box and then widen. Eg. An int can boxed to Integer and then widen to Object.
  7. var-args can be combined with either boxing or widening.

When to use interface and abstract class in Java

When to use interface and abstract class in Java?



This is very popular interview question for the beginners as well for experienced. So, Now lets talk about the interface and  abstract class.
What is interface?
 Interface is used when you just want to define the contract only and you don't know anything about implementation. (So here it is fully abstraction as you don't know anything.). That’s mean, in interface you can only define the methods and the implantation of these methods will be define somewhere else.

What is Abstract class?
Abstract class is used when you know something and depend upon other for you don’t know. By using abstract class, you can achieve partial abstraction.

So, Now lets understand the difference in Realtime example.
When to use Interface
Consider we want to start a service like "makemytrip.com" or "expedia.com",  where we are responsible for displaying the flights from various flight service company and place an order from customer.
Lets keep our service as simple as,

  1. Displaying flights available from vendors like "airasia", "british airways" and "emirates".
  2. Place and order for seat to respective vendor.
In this scenario, interface is useful or abstract class?
Remember, In this application, we don't own any flight. we are just a middle man/aggregator and our task is to first enquire "airasia", then enquire "british airways" and at last enquire "emirates" about the list of flights available and later if customer opts for booking then inform the respective flight vendor to do booking.


For this, first we need to tell "airasia", "british airways" and "emirates" to give us list of flights, internally how they are giving the list that we don't care.

  1. This means I only care for method name "getAllAvailableFlights()"

    "getAllAvailableFlights()" from "airasia" may have used SOAP service to return list of flights.
    "getAllAvailableFlights()" from "british airways" may have used REST service to return list of flights.
    "getAllAvailableFlights()" from "emirates" may have used CORBA service to return list of flights.

    but we don't care how it is internally implemented and what we care is the contract method "getAllAvailableFlights" that all the flight vendor should provide and return list of flights.

  1. Similarly, for booking I only care for method name "booking()" that all vendors should have, internally how this vendors are doing booking that I don't care.

To conclude: We know contract. 
So we can say that we know the contract that irrespective of who the Flight vendor is, you need "getAllAvailableFlights()" and "booking()" method from them to run our aggregator service.

In this situation, Interface is useful because we are not aware of the implementation of all the 2 methods required, and what we know is the contract methods that vendor(implementer) should provide. so due to this total abstraction and for defining the contract, interface is useful in this place.
Technically, we need to design our interface somewhat like below,
FlightOpeartions.java(Contract) 
interface FlightOpeartions{

 void getAllAvailableFlights();

 void booking(BookingObject bookingObj);

}
BookingObject.java 

class BookingObject{}
BritishAirways.java (Vendor 1) 

class BritishAirways implements FlightOpeartions{



 public void getAllAvailableFlights(){

           //get british airways flights in the way

           //they told us to fetch flight details.

 }



 public void booking(BookingObject flightDetails){ 

          //place booking order in a way British airways

          //told us to place order for seat.

 }



}
Emirates.java (Vendor 2) 

class Emirates implements FlightOpeartions{



 public void getAllAvailableFlights(){

         //get Emirates flights in the way

         //they told us to fetch flight details.

 }



 public void booking(BookingObject flightDetails){ 

         //place booking order in a way Emirates airways

         //told us to place order for seat.

 }

}

How Interface achieve Polymorphism.

Note:
Interface just speak about the contract capabilities and don't know anything about implementation.

Example: 
Interface can very well say that "I can get all available flights", "I can do booking" because they have that capability, but they don't know "How exactly to get all available flights", "How exactly to do booking" and this is the job of class that accepted Interface contract in other words it is the job of class that implements that interface.

Interface helps in achieving dynamic Polymorphism because it focus only on capabilities and don't care about implementation which implemented class MUST take care of as define in interface contract.
Interface very well knows what methods it is capable of calling, and it is sure that class that implements this interface definitely has given the body to those methods, so it blindly calls  

"interfaceReference.capableMethods()",  
(in our example: flightOperationsReference.getAllAvailableFlights())

It doesn't care, what object has been assigned to "interfaceReference", (it can be of any class that implemented it), but when interface calls "interfaceReference.capableMethods()",  "capableMethods()" method will definitely be called on class whose object has been assigned to "interfaceReference" and that is the contract that every implementer of interface should provide body to methods defined in interface.



When to use Abstract class
Scenario, 
Consider we want to start a service like Bulk SMS sender, where we take orders from various telecom vendors like Airtel, France Telecom, Vodafone etc.

For this, we don't have to setup your own infrastructure for sending SMS like Mobile towers but we need to take care of government rules like after 9PM, we should not send promotional SMS, we should also not send SMS to users registered under Do Not Disturb(DND) service etc. Remember, we need to take care of government rules for all the countries where we are sending SMS.

Note: for infrastructure like towers, we will be relying on vendor who is going to give us order.
Example, In case of,
Vodafone request us for bulk messaging, in that case we will use Vodafine towers to send SMS. 
Airtel request us for bulk messaging, in that case we will use Airtel towers to send SMS.
What our job is to manage Telecom Regulations for different countries where we are sending SMS. 

So what all methods we require would be somewhat like below,

public void eastablishConnectionWithYourTower(){

   //connect using vendor way.

   //we don't know how, candidate for abstract method

}



public void sendSMS(){

   eastablishConnectionWithYourTower();

   checkForDND();

   checkForTelecomRules(); 

   //sending SMS to numbers...numbers.

   destroyConnectionWithYourTower()

}



public void destroyConnectionWithYourTower(){

   //disconnect using vendor way.

   //we don't know how, candidate for abstract method

}



public void checkForDND(){

   //check for number present in DND.

}



public void checkForTelecomRules(){

   //Check for telecom rules.

}
Out of above 5 methods, 

  1. Methods we know is "sendSMS()", "checkForDND()", "checkForTelecomRules()".
  2. Methods we don't know is "eastablishConnectionWithYourTower()", "destroyConnectionWithYourTower()".
we know how to check government rules for sending SMS as that is what our job is but
we don't how to eastablish connection with tower and how to destroy connection with tower because this is purely customer specific, airtel has its own way, vodafone has its own way etc. 

So in the given scenario, we know some methods but there also exist some methods which are unknown and depends on customers.


In this case, what will be helpful, abstarct class or interface?


In this case, Abstract class will be helpful, because you know partial things like "checkForDND()", "checkForTelecomRules()" for sending sms to users but we don't know how to eastablishConnectionWithTower() and destroyConnectionWithTower() and need to depend on vendor specific way to connect and destroy connection from their towers.

Let's see how our class will look like,




abstract class SMSSender{

  

 abstract public void eastablishConnectionWithYourTower();

  

 public void sendSMS(){

  /*eastablishConnectionWithYourTower();

  checkForDND();

  checkForTelecomRules(); 

   

  sending SMS to numbers...numbers.*/

 }



 abstract public void destroyConnectionWithYourTower();



 public void checkForDND(){

  //check for number present in DND.

 }

 public void checkForTelecomRules(){

  //Check for telecom rules

 }

}





class Vodafone extends SMSSender{



 @Override

 public void eastablishConnectionWithYourTower() {

  //connecting using Vodafone way

 }



 @Override

 public void destroyConnectionWithYourTower() {

  //destroying connection using Vodafone way

 }

  

}



class Airtel extends SMSSender{



 @Override

 public void eastablishConnectionWithYourTower() {

  //connecting using Airtel way

 }



 @Override

 public void destroyConnectionWithYourTower() {

  //destroying connection using Airtel way

 }

  

}
Other differences between interface and abstract class in Java.

No
abstract class
interface
1
Abstract class can have both abstract methods (incomplele. methods without body) and non-abstract methods(complete. methods with body).
Interface can only have abstract methods till Java 7.
In Java 8, Interface can have non-abstract default and static methods.
2
Abstract class can extends only one class and can implements multiple interfaces.
Interface can only extends other interfaces.

 






What is Polymorphism in Java with example


What is Polymorphism in Java with example.

Polymorphism is one of the most important concept of OOPS that means "one object having many forms".

Polymorphism is a Greek word which means "Many Forms", Polymorphism = (Poly + Morphism) = Many + Forms.

 Lets understand above line in more details with example.

Every concept of OOPS also exist in Real Life, so for better understanding lets first understand real life example of Polymorphism.


Real Life example

There are many English words when used without context will have multiple meanings.
Example:

If I don't give you context and simply say word, you will not able to exactly tell what it is used for.

bear:
    • bear can be used to represent a mammal "The black bear". 
    • bear can also be used in context of pain like "I cannot bear his constant criticism".
Similarly,

close:
    • close can be used in context of opposite of far like "Please close the window".
    • close can also be used in context of opposite of open like "Please close the door".
So many words in English has multiple meanings that is "same word but multiple meanings".
Isn't it matching with our Polymorphism definition "same object many forms"!!!


In Java

Similarly in Java, there can be a situation where we need to write more than one methods with same name (because they all do the same job) but they behave differently based on the parameters supplied.

Lets take an example:


  1. getSum(int a, int b) { return a+b; } used to calculate the sum of two integer number.
  2. getSub(int a, int b, int c) { return a+b+c; } used to calculate the sum of three integer number.

If you look at above two method names "getSum", they both are doing same job of calculating sum of integer numbers, so given only name, you cannot say, whether method is used to calculate sum of two or three numbers. but you will definitely get a broad idea that method is used to calculate the sum.

Parameters supplied to the method will give the exact meaning to the method. whether it is used to calculate sum of two numbers or three numbers.

We can achieve Polymorphism in Java by,
  1. Method Overloading
  2. Method Overriding.


Another example of Polymorphism,
We use "System.out.println()" method and passed int, float, String, Object etc as a parameter like,
System.out.println(10) -> 10
System.out.println("hello") -> hello
System.out.println(50.5) -> 50.5
same method name println(), can sometime print integer, sometime float, sometime String etc.

Internally there are multiple println() method written as shown below,