Tuesday, 8 July 2014

Garbage Collector in Java

Garbage Collector is a part of JVM (Java Virtual Machine). Garbage collector(GC) only deal with heap memory.GC is a program which runs on the JVM which gets rid of objects which are not being used by a Java application anymore. It is a form of automatic memory management.


Garbage collection was invented by John McCarthy around 1959 to solve problems in Lisp.

Garbage Collector done it's job without any request and  notification.It continuously reviewing the heap memory that any objects have not been referenced to variable(stack) then it automatically clean the memory from these object or simple words are It frees memory allocated to objects that are not being used by the program any more.
In Java the GC runs automatically, but you can also call it explicitly with System.gc() and try to force a major garbage collection but in a programming language like C, allocating and deallocating memory is a manual process so Java take this headache from programmer and put it into JVM.





  public class GarbageCollector{
   public static void main(String[] args) {
        Object obj1=new Object(); //Create a new object on Heap
        obj1=new Object();//Create another object and hold reference to last one variable
        System.gc();
  }
}//ENd of Class

Now in the above code the first time obj1 hold referenced first created object and then
 it again hold another object reference; but where is the last object referenced that is
 unreachable; now it's time of Garbage collector and it automatically deallocate the 
object memory from  the heap and make available free for the future and save program
from starvation problem. 
We can garbage collector in Java by using this statement
   System.gc();

Note: If anyone don't know about the word "HEAP" or "Stack" then first 
I recommend to you read this topic
http://theprogrammingsintroduction.blogspot.com/2014/07/what-is-stack-and-heap-in-java.html

What is Exception handling in Java

Exception Handling is also known as Defensive Programming.
Exception is an indication of a problem that occurs during a program’s execution.
Exception handling enables you to create applications that can resolve (or handle) exceptions. In many cases, handling an exception allows a program to continue executing as if no problem had been encountered. The features  help you write robust and fault-tolerant programs that can deal with problems and continue executing or terminate gracefully. 
Java exception handling is based in part on the work of Andrew Koenig and Bjarne Stroustrup.

When to Use Exception Handling?
Exception handling is designed to process synchronous errors, which occur when a statement
executes. Common examples we’ll see  are out-of-range array indices, arithmetic overflow (i.e., a value outside the representable range of values), division by zero, invalid method parameters, thread interruption
and unsuccessful memory allocation (due to lack of memory). 
Exception handling is not designed to process problems associated with asynchronous events (e.g., disk I/O completions,network message arrivals, mouse clicks and keystrokes), which occur in parallel with,
and independent of, the program’s flow of control.

Hierarchy of Exception
An small portion of the inheritance hierarchy for class Throwable (a subclass of Object), which is the superclass of class Exception. Only Throwable objects can be used with the exception-handling mechanism. Class Throwable has two subclasses: Exception and Error. 
Class Exception and its subclasses—for instance, RuntimeException (package java.lang) and IOException (package java.io)—represent exceptional situations that can occur in a Java program and that can be caught by the application. Class Error and its subclasses represent abnormal situations that happen in the JVM. 

Types of Exception

  1. Checked Exception
  2. UnChecked Exception

Java compiler enforces a code written with in try/ catch block or throw an Exception object for checked exceptions.All exception types that are direct or indirect sub classes of class RuntimeException (package java.lang) are unchecked exceptions like ArrayIndexOutOfBoundsExceptions and ArithmeticExceptions. 
And other Exception known as checked Exception that are not subclass of RunTimeException class.
You must write Java code for checked exception within try catch block or use throw clause.

Here is an Example through Java Code

  public class ExceptionExample{
         public static void main(String []args){
               try{
                    // Open File and read data
               }
               catch(Exception e){
                         //TO do for to handle Exception
               }
         }
  }


OR throws example are

 public class ExceptionExample{
         public static void main(String []args) throws Exception{
              
                    // Open File and read data
              
              
         }
  }

In above throws example we don't need to write code with in try/catch block.

Hope you got the idea about the Exception handling.I know there are many other concept and techniques related Exception Handling not mentioned in here but reason for that I put consideration in my mind for all audience newbie, Beginner ,Intermediate or Expert.

What is Stack and Heap in Java


Java Memory is divided into two types

  1. Stack 
  2. Heap
Both are in RAM(Random access Machine).

All objects are stored on the heap (including their attributes).
Local variables (including arguments) always contain primitive values or references and are stored on the stack.
Here is another picture below

String s = "Hello";
In this "s" are variable that hold the address/reference of "Hello" String 
Object.
Variable is on Stack and "Hello" reference is on Heap.Java only stores primitives on
 the stack and Objects are created on the heap, and only references
(which in turn are primitives) are passed around on the stack.
Let take a look on Java Code

  public class Employee{
    public static void main(String []args){
          Employee e=new Employee();
    }
  }

In above the "e" is a variable that hold the reference/address of Employee
object and "new Employee()" actually this give the reference of newly created 
object.
Variables created on the stack will go out of scope and automatically deallocate and
whether  Variables on the heap must be destroyed manually and never fall out of scope(Garbage collector/finalize() ).
In a stack of items, items sit one on top of the other in the order they were placed 
there and you can only remove the top one (without toppling the whole thing over). 
so stack follow LIFO(Last In first Out) but  In a heap, there is no particular order to the 
way items are placed.
You can reach in and remove items in any order because there is no clear 'top' item.

Sunday, 6 July 2014

What is static in Java

Here is the key point on static

  • static is a keyword in Java
  • static variable also know as class variable.
  • static variable are belong to class instead object.
let take look on code
  public class Employee{
      static int noOfEmployee;
  }

In above "noOfEmployee" are the static variable or class variable.Class contain only one copy of this attribute even if you create thousand object.

  • static method only access static attribute instead instance variable.
  • We can access static variable by class name rather than object just like Math.PI
  • We cannot refer static variable to this keyword
Let's take another look of code

   public class Employee{
       private static int noOfEmployee;

       public int getNoOfEmployee(){
             return noOfEmployee();
       }
   }
//////////////////////////////////////////////////////////
Another most usable code  and static example is

  public class Employee{
     private static int noOfEmployee; 
     public static void main(){
           Thread.sleep(1000);
           System.out.println(noOfEmployee);
     }
  }


In above sleep is a static method of Thread class and see static method accept only static variable.
Whether instance method can contain static method.

Here is difference between the instance and class method by code


class Difference {
 
  public static void main(String[] args) {
    display();  //calling without object
    Difference t = new Difference();
    t.show();  //calling using object
  }
 
  static void display() {
    System.out.println("Programming is amazing.");
  }
 
  void show(){
    System.out.println("Java is awesome.");
  }
}

Saturday, 5 July 2014

Encapsulation V/S Abstraction

Abstraction and Encapsulation are basically interdependent with each other.If you want to achieve Abstraction then Encapsulation should use for it and same case other. 
Lets take look on example by Java Coding
    

    abstract class Person{
    private int personId;
    private String name;

    public int getPersonId() {
        return personId;
    }

    public String getName() {
        return name;
    }

    public void setPersonId(int personId) {
        this.personId = personId;
    }

    public void setName(String name) {
        this.name = name;
    }

    public abstract double earning();

}//end of abstract class
public class Employee extends Person{

    private double salary;

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    
    
    @Override
    public double earning() {
       return this.salary;
    }
  
}

 - Abstraction mean we know what is this but don't know how is this and Encapsulation mean we hide information from user.
 - Abstraction come from abstract classes or interface  and Encapsulation come from
   access modifier + getter/setter method. 
 - Abstraction give you Polymorphism and Encapsulation give you information hiding.

Wednesday, 2 July 2014

What is Interface in Java

Interface is just like Java class but it contain only abstract method and final attribute.

E.g
       public interface Employee{
                   public void earning(); 
       }

in this "interface" is a keyword and "Employee" is an identifier, in interface all method by default are public and abstract; so you don't need to write otherwise there are also no problem you can also write this

     public interface Employee{
            abstract public void earning();
     }


. Basically interface are used to achieve "Polymorphism".
It's also possible that an interface can inherit / extends to another interface , here is an example

   public interface CivilEmployee extends Employee{
               public void getRetirementAge(); 
   }   


  Now here to explain how to use and how to implements the interface and An interface is a "contract" where the class that implements the contract promises to implement the methods.

    public class PermanentEmployee implements CivilEmployee{
              @Override 
              public void earning(){
               // Do what do you want
              }

             @Override 
              public void getRetirementAge(){
                     //DO what do you want in this methoid
              }
    }

In this example I use annotation @Override this mean that force to compiler check the method signature with interface method signature ; if it not match then give the compile time error.


Similarly abstract class , object of interface class cannot be instantiate; but major difference between interface and abstract class are

  • interface contain only all abstract method whereas abstract can contain concrete method
  • You can implements more than one interface whereas through abstract class you can extends single abstract calss.
  • interface are like rule and abstract classes are guideline.
  • interface are use when we know what to do but don't know how to do but opposite in abstract class we know what to do but some how know how to do
Consider we have a Payment class. payment can be done in so many ways like paypal, credit card So we normally take Payment as our interface which contains makePayment() method and CreditCard and PayPal are the two implementation classes.

public interface Payment
{
    void makePayment();//by default it is a abstract method
}
public class PayPal implements Payment
{
    public void makePayment()
    {
        //some logic for paypal payment
        //like paypal uses username and password for payment
    }
}
public class CreditCard implements Payment
{
    public void makePayment()
    {
        //some logic for CreditCard payment
        //like CreditCard uses card number, date of expiry etc...
    }
}
Similarly like abstract classes are
 public abstract class Burger
{
    public void packing()
    {
        //some logic to packing a berger
    }
    public abstract void price();//here price is different for different catagories.Thats why abstract method
}
public class VegBerger extends Burger
{
    public void price()
    {
        //set price for a veg burger.
    }
}
public class NonVegBerger extends Burger
{
    public void price()
    {
        //set price for a non-veg burger.
    }
}

Sunday, 29 June 2014

What is Abstract Class in Java

Here are the points related Abstract class in Java that shall clear about Abstract word
  1. Abstract class is the one of class that cannot be instantiated.
  2. If you want to get implementation of any method from child class(other person) then abstract method can use in this sense.
  3. Abstract class are incomplete ,subclass must declare missing piece to become concrete class(Class whose object can be instantiated ) , otherwise these subclass also become abstract class.
  4. You can achieve abstraction that is main pillar of OOP through by "abstract classes".
  5. Abstraction hide the irrelevant detail of an object.
  6. Abstract use for IS A Relationship (Inheritance).
  7. Abstraction use for to achieve Polymorphic behavior (Another main pillar of OOP)   
Here is example of abstract class
   abstract public Employee{

         abstract public void earning();// abstract method

         public void showAge(){//concrete method
                System.out.println("My Age ??");
          }
   }

   8. abstract class should not be private and not contained private method.
   9.  You extends single abstract class not multiple because Java is Single supported Inheritance
   10.  Abstract class must contain  1 or more than 1 abstract method
   11.  If any class contain abstract method then it should explicitly declare abstract class even if it contain 
        concrete method.
   12. Constructor and static method cannot be declared as abstract because constructor are not inherited.

   public class HourlyEmployee extends Employee{
             
        public void earning(){// Implementation of  Abstract Method
                System.out.println("My Earning ");
        }

      @Override
      public void showAge(){
                System.out.println("My Age ??");
      }
   }//end of class

   13. If child class have not implement the abstract method of super class then it become also abstract class.
   14. Attempting to instantiate the object of abstract class is an Compilation error.
   15. Abstract super class variable can hold the reference of child concrete object.


     Employee e=new HourlyEmployee();

Friday, 27 June 2014

Why Java

If you want to learn OOP (Object Oriented Programming) with learning Programming then Java is the top most and recommended  Proramming language.Here is the following why I said above statement



  • Java Inherit from C and C++ language ; if you know C /C++ language then there is no problem for you to learn instead from scratch
  • Java is Pure Object Oriented
     All work in the Java is in Classes and objects that is the key element of OOP.
    public class Welcome{
           public static void main(String []args){
                System.out.println("Welcome to my Blog);
    }
    }

    In the above program of Java , If you want to take little bit from Java then you should work in the classes
  • It's give you more than 5000 built in classes that make your easier and faster.
    E.g : If you want to make connection to other using WEB then you can use java.net package.
  • You can run your own Java Application in to any other Platform.
  • There are larger community and forums for Java ,if you feel and face any sort of problem then you may ask
  1.  StackOverflow
  2. Programmer
  3. CodeRanch
  4. Android.Developer