Friday, 2 February 2018

Abstract class Vs Interface in java

Abstract class and interface differ based on following parameters:


Methods

An abstract class can have both abstract methods and concrete methods.
An interface has all the methods as abstract. Methods in interface is 100% abstract.

Keyword used to declare

To declare abstract class use the keyword ‘abstract’. 
Example abstract class dummyClass{//abstract methods, methods}

To declare interface use the word ‘interface’. 
Example interface dummyInterface{//abstract method (s)}

Method declaration

In abstract class, to declare any method as abstract use of abstract keyword is mandatory.
In interface, to declare methods as abstract use of abstract keyword is optional. Methods in interface is by default abstract.

Inheritance Supported

Being a class, an abstract class cannot inherit multiple classes. It can only inherit one class.
An Interface can extend (or inherit) multiple interfaces.

What can be extended?

An abstract class can extend either normal class or abstract class.
Interface can extend only interface but not a class.

Variable type & Access modifier

An abstract class can have static, non-static, final or non-final variable with any access modifier.
An interface can only have public static final variable. In interface variable is constant.

Friday, 15 December 2017

Difference: Array vs Vector in java

Array and Vector differs based on the following parameters:

Basic:

Array in java is an object that contains data of homogeneous (similar) type.
example, int a[]={5,6,4,55}; //this array can only store int data type

Vector can store heterogeneous data types, if restriction is not put using generics concept. See the example below:

package string;

import java.util.Iterator;
import java.util.Vector;

public class splitDemo {

      public static void main(String[] args) {

            Vector v = new Vector();
            v.add(1);    //integer
            v.addElement("xyz");  //string
            v.add('s');  //char

            Iterator itr = v.iterator();
            while(itr.hasNext()){
                  System.out.println(itr.next());
            }
      }
}

OUTPUT:
1
xyz

In above example, you can see we have stored int, String and char objects in vector. 

Note: To make vector store homogeneous data type do the following:

Vector<String> v = new Vector<String>();

This will only allow storage of String object in vector.

Family:

Array does not belongs to Collection family. It is a primitive data type.

Vector implements List interface which is a part of collection hierarchy. Thus vector is a part of collection family.

Size:

Array needs to be assigned with the fixed size during initialization thus making it static in nature.

Vector resizes itself dynamically as per the need. Thus it is dynamic in nature.

Synchronized:

Array is non-synchronized in java.

Vector is synchronized in java.

Traversal:

Array can be traversed using for loop or enhanced for loop. It cannot use iterator or enumeration interface like vector or arraylist.

Vector can be traversed using iterator or enumeration interface

Declare/Instantiate/Initialization:

Array
Integer array
int a[]={5,6,4,55};

String array
String a[]={"Ajay","vijay","Rajesh","Mukesh"};

Similarly you can do for other data types like double, float, char, etc

Vector
Vector<String> vec=new Vector<String>();  //create vector
vec.add("Ajay");      //add element to vector
vec.add("vijay");




You may also like to read:

Wednesday, 13 December 2017

Difference: ArrayList vs CopyOnWriteArrayList in java

ArrayList and CopyOnWriteArrayList in java differ based on following parameters:

1. Inclusion in java

Arraylist was added in Java 1.2 version.

CopyOnWriteArrayList was added in Java 1.5 or Java 5.


2. Thread-safety

Arraylist in java is not synchronized thus is not at all thread safe.

CopyOnWriteArrayList is synchronized in nature. Thus it is thread safe and for the same reason only one thread can access the resources in this class at a time.


3. Performance

As arraylist is non-synchronized so it is better performance wise as multiple threads can access the resources of arraylist at the same time simultaneously.

Being synchronized means only one thread can have access to CopyOnWriteArrayList resources thus impacting its performance speed.


4. ConcurrentModificationException

Arraylist throws ConcurrentModificationException.

CopyOnWriteArrayList doesnot throw ConcurrentModificationException.


5. Fail fast or fail safe

 Arraylist's  iterator and list iterator are fail fast in nature.

CopyOnWriteArrayList iterator are fail safe in nature.



You may also like to read:


Sunday, 13 August 2017

Difference: HashMap vs HashTable


HashMap and HashTable differ based on the following parameters:

  • Nature
           HashMap is not synchronized in nature.
           HashTable is synchronized in nature

  • Traversed by
           HashMap can be traversed by using an iterator
           HashTable can be traversed by using an iterator or enumerator

  • Null value/key
          HashMap allows only one null key and any number of null values.
          HashTable doesn't allow key or value as null.

  • fail-fast nature of iterator
          Iterator in HashMap is fail-fast.
          Enumerator in HashTable is not fail-fast.

  • Performance
          HashMap is faster performance wise.
          HashTable is slower in comparision to HashMap performance wise.
          
          Reason: Since HashTable is synchronized in nature so it doesn't allow multi-threading                                       operation on a particular resource at a time thus turning out to be slower than                                       HashMap which is non-synchronized by nature.



You may also like to read:



Sunday, 16 April 2017

Checked and Unchecked Exception in java

Two categories of Exception that we come across are:

Checked Exception:

Checked Exception extends java.lang.Exception

If there is possibility that the code written may result in throwing exception then compiler senses it and reminds programmer to handle such codes in either of these two ways during compilation:
  • enclose code within try/catch
  • declare the exception using throws keyword
At the very basic level you can think of it as exceptions which are caught at the compile time.


For example,

You have a code where you want to read a file from particular location  say ("D:\\JavaFiles\\myFile.txt")


import java.io.*;

class MyFileReader {

    public static void main(String[] args) {

        FileReader file = new FileReader("D:\\JavaFiles\\myFile.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 4 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 4; counter++)
            System.out.println(fileInput.readLine());
         
        fileInput.close();
    }
}

What would be fate of above code?

It is sure to throw compile time error.

Reason being the presence of FileReader which throws Checked Exception FileNotFoundException and readLine & close which throws checked exception IOException.

In order save your code from compile time error enclose the code within try/catch block. Or declare all Exceptions that could possibly occur using throws like this,


 public static void main(String[] args) throws IOException


Since FileNotFoundException is the child (sub class) of IOException so declaring only IOException using throws will serve the purpose here.

ExamplesSQLExceptionClassNotFoundExceptionIOExceptionetc




Unchecked Exceptions:

Unchecked Exceptions extends java.lang.RuntimeException

Unchecked Exceptions are those that goes beyond the range of compilers and escapes their notice. It occurs due to error in programming logic. There are exceptions which can only be detected at run time such as illogical codes. 

Like, a code where you perform division by 0(zero) or you try to access value from an index which is not present in the array. 

These kind of code will compile fine and will look perfect until run. So unchecked Exception are run time exceptions.

For example consider this code,

class MyFile {

    public static void main(String[] args) {
         
        // Division by 0
        int x = 5/0; // illogical code will throw ArithmeticException
        System.out.println(x);
    }
}

The above code will not show any compile time error. But if you run it, you will find ArithmeticException.

So as a programmer you are never expected to write a code like,
int i=5, int j=0;
int k=i/j;

because it is loop hole in coding logic and will show its erroneous face while you run it and will result in abrupt termination of your code if it is not taken care by try/catch block.
And if you write such code then you have to waste lot of time in debugging your code and find out this kind of logical error.

ExamplesArithmeticExceptionArrayIndexOutOfBoundsException,NullPointerExceptionsetc




You may also like to read:


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.