Difference between enumeration and iterator and listiterator?

Enumeration:

  • Enumeration interface implemented in java 1.2 version.So Enumeration is legacy interface.
  • Enumeration uses elements() method.
  • Enumeration can traverse in forward direction only.
  • Enumeration having methods like hasMoreElement(),nextElement().

Program:

package com.instanceofjavaforus;
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] args) {
Vector vector=new Vector();
vector.add("indhu");
vector.add("sindhu");
vector.add("swathi");
vector.add("swathi");
vector.add(null);
vector.add(null);
Enumeration en = vector.elements();  
    while(en.hasMoreElements()){  
         System.out.println(en.nextElement());  
    }  
}
}

Output:

indhu
sindhu
swathi
swathi
null
null

Iterator:

  • Iterator is implemented on all Java collection classes.
  • Iterator uses iterator() method.
  • Iterator can traverse in forward direction only.
  • Iterator having methods like hasNext(), next(), remove().

Program:

package com.instanceofjavaforus;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class IteratorDemo{
public static void main(String[] args) {
TreeMap treeMap=new TreeMap();
treeMap.put("g", "indhu");
treeMap.put("d", "sindhu");
treeMap.put("3", "swathi");
treeMap.put("d", "sindhu");
if(!treeMap.isEmpty()){
Iterator it=treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}
}
}

}


Output:

swathi
sindhu
indhu

ListIterator:

  • ListIterator is implemented only for List type classes
  • ListIterator uses listIterator() method.
  • ListIterator can traverse in forward and backward directions.
  • ListIterator having methods like 
  • hasNext()
  • next()
  • previous()
  • hasPrevious()
  • remove()
  • nextIndex()
  • previousIndex().

Program:

package com.instanceofjavaforus;
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorDemo{
public static void main(String[] args) {
ArrayList arrayList=new ArrayList();
arrayList.add("indhu");
arrayList.add("sindhu");
arrayList.add("saidesh");
arrayList.add(null);
arrayList.add(null);
ListIterator it=arrayList.listIterator();
while(it.hasNext()){
System.out.println(it.next());
}
}

}

Output:
indhu
sindhu
saidesh
null
null


Why Java does not supports multiple inheritance?

Inheritance:

  • The concept of getting properties of one class object to another class object is known as inheritance.
  • Here properties means variable and methods.

Types of Inheritance:

  1. Multiple inheritance.
  2. Multilevel inheritance.

 Multiple inheritance:


  • The concept of Getting the properties from multiple class objects to sub class object with same priorities is known as multiple inheritance.
  • Java Doesn't Support multiple Inheritance.

Diamond problem:

  • In multiple inheritance there is every chance of multiple properties of multiple objects with  the same name available to the sub class object with same priorities leads for the ambiguity.

  1. //Multiple inheritance program
  2. Class A{
  3. }
  4. Class B extends A{
  5. public void show(){
  6. }
  7. }
  8. Class C extends A{
  9. public void show(){
  10. }
  11. }
  12. Class D extends B,C{  // not supported by java leads to syntax error.
  13. }


Why multiple inheritanc eis not possible in java




  •  We have two classes B and c which are inheriting A class properties.
  • Here Class D inheriting B class and C class So properties present in those classes will be available in java.
  • But both classes are in same level with same priority.
  • If we want to use show() method that leads to ambiguity
  • This is called diamond problem.
  • Because of multiple inheritance there is chance of the root object getting created more than once.
  • Always the root object i.e object of object class hast to be created only once.
  • Because of above mentioned reasons multiple inheritance would not be supported by java.
  • Thus in java a class can not extend more than one class simultaneously. At most a class can extend only one class.
So these are the reasons that java does not supports multiple inheritance.Even though having this much reasons some people say and we also gets some doubts when we are using interfaces. lets me clear this one also. our immediate question should be.

Is Java supports multiple inheritance using interfaces?

  • Before that we need to know about interfaces.
  • Interfaces having fully abstract functionality.
  • Means methods in interfaces by default public abstract methods so we need to implement these methods in classes which are extending this interface.
   
  1. /Multiple inheritance program
  2. interface A{
  3. public void  show();
  4. }
  5. interface B{
  6. public void  display();
  7. }
  8. Class C Implements A,B{
  9. }



  • Here it seems we are achieving multiple inheritance by using interfaces. but we are not.
  • Syntactically it seems to multiple inheritance but the actual implementation of multiple inheritance is not there. how can i say that? let me clear

Difference between interfaces and inheritance: in multiple inheritance

  • Inheritance means getting the properties from one class object to another class object.
  • Means if any class extending another class then the super class methods can be used in sub classes happily.
  • But in interfaces the methods in interfaces are fully abstract so we need to provide functionality in our extended class and use it .seems both are opposite right? yes.
  • That is the reason we can say interfaces are only supports syntactical multiple inheritance which is not implementation of multiple inheritance.
So finally java supports only syntax of multiple inheritance does not supports implementation of multiple inheritance.
Inheritance is like debit and interface is like credit but interface has its own importance in other concepts like server side programming

What is the major change in JAVA 8 regarding interfaces:

5 different places to define Object of a class in java

different places to define object of a class


  • Object of a class can be defined at 5 different places.
  1. Defining object of a class as local to a method or local variable.
  2. Defining object of a class as an instance variable of another class.
  3. Defining object of a class as the parameter of the method.
  4. Defining  object of a class as the return data type of the method.
  5. Defining object of a class as the static variable or class variable of another class.

1.Defining object of a class as local to a method or local variable:


  1. package com.instanceofjava;
  2.  
  3.  public class ObjectInsideMethod { 
  4.  
  5.    int val;  
  6.  
  7. public int getVal()
  8.  {     
  9.   
  10.   return val;   
  11.  
  12.   }
  13.  
  14. public void setVal(int val) {  
  15.  
  16.        this.val = val;
  17.  
  18.  }
  19.  
  20. public void createObject(){ 
  21.   
  22.        ObjectInsideMethod obj=new ObjectInsideMethod();        
  23.         obj.setVal(10);    
  24.  
  25.       System.out.println(obj.getVal());
  26.  
  27.   }
  28.  
  29.    public static void main(String[] args) {
  30.  
  31.         ObjectInsideMethod obj=new ObjectInsideMethod();
  32.         obj.createObject();
  33.  
  34.  }
  35. }





2.Defining object of a class as an instance variable of another class:


  1. package instanceofjava;
  2.  
  3. class sample{
  4.  
  5.   int num;
  6.  
  7. public void setNum(int num) {
  8.         this.num= num;
  9. }
  10.  
  11. public String getNum() {
  12.         return num;
  13.     }
  14. }



  1. package com.instanceofjava; 
  2.  
  3. public class ObjectAsInstanceVariable { 
  4.  
  5.  Sample sample= new Sample ();   
  6.  
  7. public static void maina(String args[]){  
  8.  
  9.      ObjectAsInstanceVariable obj=new ObjectAsInstanceVariable();    
  10.      obj.sample.setNun(10);    
  11.  
  12.     }
  13.   }  



3.Defining object of a class as the parameter of the method.


  1. package com.instanceofjava; 
  2.  
  3.  public class Employee 
  4. {  
  5.  
  6.    String name;  
  7.    int id;   
  8.    String address;    
  9.  
  10. Employee(String name, int id, String address){ 
  11.  
  12.         this.name=name; 
  13.         this.id=id; 
  14.         this.address=address; 
  15.  }   
  16.  
  17.  public boolean comapreEmpids(Employee e){
  18.  
  19. if(this.id==e.id){ 
  20.  
  21. return true;  
  22.  
  23. }
  24. return false;
  25. }   
  26.  
  27.  public static void main(String args[]){
  28.  
  29.      Employee empone= new Employee("sai", 1, "hyderabad");
  30.      Employee emptwo= new Employee("sai", 2, "Khammam");
  31.  
  32.      boolean check=empone.comapreEmpids(emptwo);
  33.      System.out.println(check); //returns false
  34.  
  35.     } 
  36. }

 

 4.Defining  object of a class as the return data type of the method.


  1. package com.instanceofjava;  
  2.  
  3. public class Singleton
  4. {

  5. static Singleton obj;
  6.  
  7.  private  Singleton(){
  8.  } 
  9.  
  10. public static Singleton getInstance(){
  11.  
  12. if(obj!=null){ 
  13. return  obj; 
  14. }
  15. else{
  16. obj=new Singleton();
  17. return obj;
  18. }
  19.  
  20. }
  21.  
  22. public static void main(String[] args) {
  23.  
  24.  Singleton obj=Singleton.getInstance();
  25.  Singleton obj1=Singleton.getInstance();
  26.  
  27. }
  28.  }


5.Defining object of a class as the static variable or class variable of another class


  1. package com.instanceofjavaforus; 
  2. public class Sample {
  3.  
  4.      public void diplsyString(String str){
  5.          System.out.println(str);
  6. }
  7.  
  8.  
  9.  
  10. package com.instanceofjavaforus;
  11.  
  12. public class TestDemo {
  13.  
  14.   public static Sample sample= new Sample();
  15.  
  16.   public static void main(String args[]){
  17.  
  18. TestDemo.sample.diplsyString("Hello Hyderabd");
  19.  
  20.  }
  21. }


This scenario used in System.out.println();

Five different ways to create objects in java?


    There are four different ways to create objects in java:

  1.     Using new keyword
  2.     Using Class.forName():
  3.     Using clone():
  4.     Using Object Deserialization:  
  5.     Using newIntance() method

Using new keyword:


    This is the most common way to create an object in java. Almost 99% of objects are created in this way.

MyObject object=new Object();

Using Class.forName():

  • If we know the name of the class & if it has a public default constructor we can create an object in this way.
  • Syntax:
  • Myobject obj=(MyObject) class.forName("object").newInstance();




Using clone():


  • The clone() can be used to create a copy of an existing object.
  • Syntax:
  • MyObject obj=new MyObject();
  • MyObject object=(MyObject )obj.clone();

Using Object Deserialization:

  • Object deserialization is nothing but creating an object from its serialized form.
  • Syntax:
  • objectInputStream istream=new objectInputStream(some data);
  • MyObject object=(MyObject) instream.readObject();

Using newInstance() method

Object obj = DemoClass.class.getClassLoader().loadClass("DemoClass").newInstance();

Java Program on creating object using new keyword:


    package com.instanceofjava;
    
    public class Employee
    {
    
    private int id;
    private String name;
    
    Employee(int id,String name){
    this.id=id;
    this.name=name;
    }
    
    public void display(){
    
    System.out.println(id+" "+name);
    
    }
    
    public static void  main (String args[]){

    Emploee e=new Employee(1,"Indhu");
    Employee e1=new Employee(2,"Sindhu");
    
    e.display();
    e1.display();
    
    }
    }

 Output:

    Indhu
    Sindhu

Java Program on creating object using clone() method:


    package com.instanceofjava;
    
    public class Empcloneable implements Cloneable {
    
      int a;
      String name;
    
    Empcloneable(int a,String name){
    
     this.a=a;
     this.name=name;
    
    }
    
     public Empcloneable clone() throws CloneNotSupportedException{
    
      return (Empcloneable) super.clone();
    
     }
    
    public static void main(String[] args) {

    Empcloneable e=new Empcloneable(2,"Indhu");
    System.out.println(e.name);
    
    try {

    Empcloneable b=e.clone();
    System.out.println(b.name);
    
    } catch (CloneNotSupportedException e1) {
    
     e1.printStackTrace();
    }
    
    }
    }


 Output:

    Indhu
    Indhu

Java Program on creating object using Deserialization


    package com.instanceofjava;
    import java.io.*;
    public class Files
    {
    
    public static void main(String [] args)
    {
    
     Employee e = null;
    
    try
    {
    
    FileInputStream fileIn = new FileInputStream("/E/employee.txt");
    ObjectInputStream in = new ObjectInputStream(fileIn);
    
    e = (Employee) in.readObject();
    in.close();
    fileIn.close();
    
    }catch(IOException i)
    {
    i.printStackTrace();
    return;
    
    }catch(ClassNotFoundException c)
    {
    System.out.println("Employee class not found");
    c.printStackTrace();
    return;
    }
    
    System.out.println("Deserialized Employee...");
    System.out.println("Name: " + e.name);
    
    }
    
    }


 Output:

    Name:Indhu





Java Program on creating object using class.forName();


    package com.instanceofjava;
    public class Sample{
    
    public static void main(String args[]){
    
    try {
    
     Class s= Class.forName("com.instanceofjava.Sample");
     Sample obj=(Sample) s.newInstance(); 
     System.out.println(obj.hashcode());
    
     } catch (Exception e) {
    
      e.printStackTrace();
    
    }
    
    }
    
    }

 Output:

    2007759836

You Might Like:

1.What are all the Five different places to create object in java



3.Six different ways to iterate list in java

Collections Map

Map:
  • Map is key-value pair.
  • Map Interface represents a mapping between key and value.
  • Map having:
  1. HashMap
  2. LinkedHashMap
  3. HashaTable
  4. TreeMap

HashMap:
  • HashMap is not synchronized.
  • Hashmap allows one key null and multiple null values.
  • HashMap default capacity is :
static final int DEFAULT_INITIAL_CAPACITY =16 static final float DEFAULT_LOAD_FACTOR = 0.75f;
Program for HashMap:

package com.instanceofjava;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Hashmap2 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap map=new HashMap();
map.put(1, "indhu");
map.put("d", "sindhu");
map.put("3", "swathi");
map.put(null, "indhira");
map.put(null, "indhira");
map.put(4, "sindhu");
if(!map.isEmpty()){
Iterator it=map.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}
}
}


Output:
indhira
swathi
indhu
sindhu
sindhu

HashTable:
  • HashTable is synchronized.
  • HashTable doesn't allow any null key or any null values.
  • HasTable Default capacity:
static final int DEFAULT_INITIAL_CAPACITY = 11;static final float DEFAULT_LOAD_FACTOR = 0.75f;
Program for HashTable:

package com.instanceofjava;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Hashtable3{

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Hashtable hashTable=new Hashtable();
hashTable.put(1, "indhu");
hashTable.put("d", "sindhu");
hashTable.put("3", "swathi");
hashTable.put("d", "sindhu");
if(!hashTable.isEmpty()){
Iterator it=hashTable.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}


}
}

}


Output:
swathi
sindhu
indhu

TreeMap:

  • TreeMap is sorted order.
  • TreeMap doesn't allow null key or null values.



Program for TreeMap:

package com.instanceofjava;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class Employee{

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap treeMap=new TreeMap();
treeMap.put("g", "indhu");
treeMap.put("d", "sindhu");
treeMap.put("3", "swathi");
treeMap.put("d", "sindhu");
if(!treeMap.isEmpty()){
Iterator it=treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}


}
}

}

Output:

swathi
sindhu
indhu



Producer consumer problem


Common   class
package com.instanceofjavaforus;

public class Common {

    int x;
   
    boolean flag=true;
    //if flag is true producer thread has to produce
    // if flag is false consumer thread has to produce

    synchronized public void produce(int i){
       
        if(flag){
           
            x=i;
            System.out.println("producer thread has produced "+i);
            flag=false;
            notify();
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }      
        }
     }
   

    synchronized public int consume(){
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
        flag=true;
        notify();
        return x;
    }
   
}

package com.instanceofjavaforus;

public class ProducerThread extends Thread {
    Common c;
   
    ProducerThread(Common c){
        this.c=c;
    }
   
    public void run(){
        int i=0;
        while(true){
           
            i++;
            c.produce(i);
           
           
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    } 
}

ConsumerThread:

package com.instanceofjavaforus;

public class ConsumerThread extends Thread {
   
    Common c;
   
    ConsumerThread(Common c){
        this.c=c;
    }
   
    public void run(){
       
        while(true){
           
            int x=c.consume();
            System.out.println("Consumer consumes"+x);
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    }
}

ProducerConsumerTest:

package com.instanceofjavaforus;

public class ProducerConsumerTest {
   
    public static void main(String args[]){
        Common c= new Common();
        ProducerThread pt=new ProducerThread(c);
        ConsumerThread ct= new ConsumerThread(c);
        pt.start();
        ct.start();
    }
}

Output:

producer thread has produced 1
Consumer consumed 1
producer thread has produced 2
Consumer consumed 2
producer thread has produced 3
Consumer consumed 3
producer thread has produced 4
Consumer consumed 4
producer thread has produced 5
Consumer consumed 5
producer thread has produced 6
Consumer consumed 6








Select Menu