Wednesday, January 10, 2018

Object Oriented Principles

Object Oriented programming suggests to use the following principles during the design of a software.  

Encapsulation :

Manipulation of an object’s variables by other objects or classes is discouraged to ensure data encapsulation. A class should provide methods through which other objects could access variables.  Java deletes the no longer used objects(Garbage Collection).

Abstraction :

Means, first define a class containing the variables and the behavior (methods) and afterwards you create the real objects which then all behave like the class defined it.
A class is the definition of the behavior and data. A class can not be directly be used.
A object is an instance of this class and is the real object which can be worked with.

Polymorphism :

The ability of object variables to contain objects of different classes. 


Friday, November 10, 2017

Create Schedulers in Java

At a particular point of time every developer needs to run some task background.  In java we have background clean up program nothing but Garbage Collection.

Every developer can achieve these background tasks by using java threads concepts.

They are as follows,
  1. using Simple Thread
  2. using ScheduledExecutorService
  3. using timer task

Using Simple Thread :

This simple thread is very easy to implement. Create a thread and put it in a while loop to execute forever. This will run the thread forever at back end. Provide thread methods to provide interval for running.

public class SimpleThreadTask{
public static void main(String[] args) {
  // run in for every 10 seconds
  final long timeInterval = 10000;
  Runnable runnable = new Runnable() {
  public void run() {
    while (true) {
      // ------- YOur code to run a task 
      System.out.println("Hello !!");
      // ------- ends code
      try {
       Thread.sleep(timeInterval);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      }
    }
  };
  Thread thread = new Thread(runnable);
  thread.start();
  }
}



Using ScheduledExecutorService:

This ScheduledExecutorService is provide in Java 5. 

Friday, March 4, 2016

Difference between Static binding and Dynamic binding in java ?

Difference between Static binding and Dynamic binding in java ?

Static binding : Occurs during compile time . Uses type(Class) information for binding.
      Actors :  Overloaded methods
Dynamic binding :   Occurs during run-time. Uses instance of class(Object) to resolve calling of method at run-time.
      Actors : Overridden methods

Call By Value and Call By Reference

How Java pass parameters to method ? Call by Reference or Call by Value ?


One of the tricky parts of java to understand, whether it support call by value or call by reference while using methods. Java supports both of them based on the type of the passed parameter. Let's dive into that.

Call By Value and Call By Reference :

There are two ways to pass an argument to a method
  1. call-by-value : In this approach copy of an argument value is pass to a method. Changes made to the argument value inside the method will have no effect on the arguments.
  2. call-by-reference : In this reference of an argument is pass to a method. Any changes made inside the method will affect the agrument value.
Here is the point to remember :  In Java, when you pass a primitive type to a method it is passed by value whereas when you pass an object of any type to a method it is passed as reference.
That's it Happy Learning!!!!!!

Friday, February 5, 2016

How hashCode and equals method works in HashMap or HashTable


How hashCode and equals method works in HashMap or HashTable?

Ans)  HashMap or HashTable or ConcurrentHashMap are used based on requirements when there are key value storage needed.  We should remember HashMap is backed by array in Java we will call it as bucket. 
whenever you use a get(key) method of hashcode the following are happened. 
1. Key.hashCode() method is used to find the bucket location in backing array. 
2.    In bucket, key and values are stored in form of a nested class called Entry.  If there is only one Entry at bucket location then, value from that entry is returned. 
Till now it's easy.. right? Now if the two keys has same hashcode then, we need a bit tricky to get the value for proposed key.  In this situation,  during put() operation collision had occurred, which means multiple Entry object stored in a bucket location. Each Entry keep track of another Entry, forming a  linked list data structure there.
Now the trace goes as follows,
1.   Call hashCode() method of key to find bucket location.
2.   Traverse through linked list, comparing keys in each entries using keys.equals() until it return true.
So, we use equals() method of key object to find correct entry and then return value from that. Remember key.equals() method. Many programmers mention value.equals(), which may be due to interview nervousness, but that’s incorrect. Since you don't have value object passed to get() method, there is no question of calling equals and hashCode() method on value object.  

That's it... Happy Learning!!!!



Wednesday, March 11, 2015

when to use ThreadLocal class in java

MultiThreaded Programming is always special in java. It has lot to do. In such cases we will face problems like sharing of variables (which has static specifier in my case). Synchronization is not exactly suitable then we can use thread local.
Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.

ThreadLocal class is extend in Java 8 with a new method withInitial() that takes Supplier functional interface as argument. So we can use lambda expressions to easily create the ThreadLocal instance.
Here is a small example showing use of ThreadLocal and proving that every thread has it’s own copy of ThreadLocal variable.
public class XmlParserProcessor {
//Variable for each thread stack when more number of threads running simultaneously .
    public static final ThreadLocal<Integer> count = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue()
        {
            return 0;
        }
    }; 

 public static void set(int skippedCount) {    
        skippedListCount.set(skippedCount);    
    }
    public static void unset() {    
        skippedListCount.remove();    
    }
    public static int get() {        
        return skippedListCount.get();    
    }

}

Tuesday, December 23, 2014

Java Memory Areas

Java Memory Areas



Java program has one or more threads. Each thread has its own stack.  All threads share same heap 




JVM Machine Architecture


Java Implementation :




  • Compiler and Virtual Machine
  • Compiler produces bytecode
  • Virtual machine loads classes on demand, verifies bytecode properties, interprets bytecode
  • Why this design?  Bytecode interpreter/compilers used before Pascal “pcode”; Smalltalk compilers use bytecode Minimize machine-dependent part of implementation Do optimization on bytecode when possible Keep bytecode interpreter simple For Java, this gives portability Transmit bytecode across network.


Monday, December 22, 2014

Interview Questions on java

What is the Difference between JDK and JRE?

Ans :  The “JDK” is the Java Development Kit i.e., the JDK is bundle of software that you can use to develop Java based software.
The “JRE” is the Java Runtime Environment i.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs.

Typically, each JDK contains one (or more) JRE’s along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.


Describe what happens when an object is created in Java?
Several things happen in a particular order to ensure the object is constructed properly: 1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its super classes. Implementation-specific data includes pointers to class and method data. 2. The instance variables of the objects are initialized to their default values. 3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. 4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

In Java, you can create a String object as below : String str = "abc"; & String str = new String("abc"); Why cant a button object be created as : Button bt = "abc"? Why is it compulsory to create a button object as: Button bt = new Button("abc"); Why this is not compulsory in String’s case?
Button bt1= "abc"; It is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. That simple. The only object in Java that can be assigned a literal String is java.lang.String. Important to not that you are NOT calling a java.lang.String constuctor when you type String s = "abc"; For example String x = "abc"; String y = "abc"; refer to the same object. While String x1 = new String("abc");
String x2 = new String("abc"); refer to two different objects.


What is the advantage of OOP?
You will get varying answers to this question depending on whom you ask. Major advantages of OOP are:
1. Simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear;
2. Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system;
3. Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods;
4. Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones;
5. Maintainability: objects can be maintained separately, making locating and fixing problems easier;
6. Re-usability: objects can be reused in different programs.