Tuesday, May 8, 2018

Swap 2 numbers without using temp variable

Swapping two numbers has been a very common problem in day to day use. Usually people use the approach of a temp variable where they store the value in a temp variable, do the assignment of other variable and restore second variable from temp.

Swap using a temp variable:
swap(int a, int b) {
      int temp = a;
      a = b;
      b = temp;
}

Swap with no temp variable: This approach uses XOR bitwise operation to swap the variables.

swap(int a, int b) {
      a = a ^ b;
      a = a ^ b;
      a = a ^ b; 
}

Swap with no temp variable: This approach uses addition substraction.
swap(int a, int b) {
      a=a+b; //a=15 (5+10)
      b=a-b; //b=5 (15-10)
      a=a-b; //a=10 (15-5)
}

Abstract Class in Java

Question

What is an abstract class, and when should it be used?

Answer

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Let's look at an example of an abstract class, and an abstract method.
Suppose we were modeling the behavior of animals, by creating a class hierarchy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well like eating and sleeping. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an abstract method for making a sound (such as a dog barking, a cow mooing, or a pig oinking). 

public abstract Animal
{
   public void eat(Food food)
   {
        // do something with food.... 
   }
 
   public void sleep(int hours)
   {
        try
        {
               // 1000 milliseconds * 60 seconds * 60 minutes * hours
               Thread.sleep ( 1000 * 60 * 60 * hours);
        }
        catch (InterruptedException ie) { /* ignore */ } 
   }
 
   public abstract void makeNoise();
}
Note that the abstract keyword is used to denote both an abstract method, and an abstract class. Now, any animal that wants to be instantiated (like a dog or cow) must implement the makeNoise method - otherwise it is impossible to create an instance of that class. Let's look at a Dog and Cow subclass that extends the Animal class.
public Dog extends Animal
{
   public void makeNoise() { System.out.println ("Bark! Bark!"); }
}
 
public Cow extends Animal
{
   public void makeNoise() { System.out.println ("Moo! Moo!"); }
}
Now you may be wondering why not declare an abstract class as an interface, and have the Dog and Cow implement the interface. Sure you could - but you'd also need to implement the eat and sleep methods. By using abstract classes, you can inherit the implementation of other (non-abstract) methods. You can't do that with interfaces - an interface cannot provide any method implementations.
Abstract class ia a base class that provides some invariant functionality but leaves implementation of other members to inheriting classes. You can accomplish this through the use of abstract classes which are classes that must be inherited.
Abstract classes are similar to interfaces but share many features with classes. An abstract class cannot be instantiated on its own; it must be inherited first. Abstract classes can provide all some or none of the actual implementation of a class. Like interfaces they can specify members that must be implemented in inheriting

Sunday, May 6, 2018

Search for a value in a binary search tree (BST)

Java Solution:

public class SearchInBST {

    public static void main(String[] args) {
        Node root = new Node(5);
        Node node2 = new Node(2);
        Node node3 = new Node(7);
        root.left = node2;
        root.right = node3;
        Node node4 = new Node(1);
        Node node5 = new Node(3);
        node2.left = node4;
        node2.right = node5;
        Node node6 = new Node(6);
        Node node7 = new Node(8);
        node3.left = node6;
        node3.right = node7;
        Node foundElement = find(root, 3);
        if(foundElement != null){
            System.out.println("Element found");
        }else {
            System.out.println("Element not found");
        }
        System.out.println();
    }

    private static Node find(Node root, int key){
        if(root == null){
            return root;
        }
        if(root.data == key){
            return root;
        }else if(key < root.data){
            return find(root.left, key);
        }else {
            return find(root.right, key);
        }
    }

    static class Node {
        int data;
        Node left;
        Node right;

        Node(int data) {
            this.data = data;
        }
    }
}

Wednesday, May 2, 2018

Simple blocking queue in Java using wait and notify

Simple blocking queue in Java using wait and notify

package sample;

import java.util.LinkedList;
import java.util.List;

/**
 * A Queue Implementation
 * A Blocking Queue is a queue in which enQueue(insertion) and deQueue (removal) will wait and will be synchnronized.
 * This is used mostly in Producer/ Consumer problem where we generally use a ArrayBlockingQueue or LinkedBlockingQueue.
 *
 * @param <T>
 */

public class BlockingQueue<T> {
    private final List<T> queueList;   // Kept final
    private final int size;

    public BlockingQueue(int limit) {
        queueList = new LinkedList<T>();
        size = limit;
    }

    public synchronized void enqueue(T item) throws InterruptedException {
        while (size == queueList.size()) {  // if full waiting
            wait();
        }
        if (queueList.size() == 0) {   // if empty notifying others
            notifyAll();
        }
        queueList.add(item);     // adding the element
    }


    public synchronized T dequeue() throws InterruptedException {
        while (queueList.size() == 0) {  // If empty waiting...
            wait();
        }
        if (size == queueList.size()) {  // if full notifying others
            notifyAll();
        }
        return queueList.remove(0);   // Removing the element
    }
}

Java Interview Questions on OOPS

What are the principle concepts of OOPS?

There are four principle concepts upon which object oriented design and programming rest. They are:

*     Abstraction
*     Polymorphism
*     Inheritance
*     Encapsulation (i.e. easily remembered as A-PIE).


What is Abstraction?

Abstraction refers to the act of representing essential features without including the background details or explanations.


What is Encapsulation?

Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.



What is Inheritance?

*     Inheritance is the process by which objects of one class acquire the properties of objects of another class.

*     A class that is inherited is called a superclass.

*     The class that does the inheriting is called a subclass.

*     Inheritance is done by using the keyword extends.

*     The two most common reasons to use inheritance are:

*   To promote code reuse

*   To use polymorphism



What is Polymorphism?

Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.


Explain the different forms of Polymorphism.

There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:



*     Method overloading
*     Method overriding through inheritance
*     Method overriding through the Java interface


What is method overloading?

Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
Note:



*     Overloaded methods MUST change the argument list
*     Overloaded methods CAN change the return type
*     Overloaded methods CAN change the access modifier
*     Overloaded methods CAN declare new or broader checked exceptions
*     A method can be overloaded in the same class or in a subclass


What is method overriding?

Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
Note:



*     The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
*     You cannot override a method marked final
*     You cannot override a method marked static


What is an abstract class?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
Note:



*     If even a single method is abstract, the whole class must be declared abstract.
*     Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.

Categories