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








Class and object

Class

  • Class is a structure
  • Binding the data with its related and corresponding functions.
  • Class is the base for encapsulation.
  • Class is a user defined data type in java.
  • Class will act as the base for encapsulation and implement the concept of encapsulation through objects.
  • Any java applications looks like collection of classes but where as c- application looks like collection of functions.

  1. public class Example{

  2.          //variable declaration
  3.           int id;

  4.       // methods
  5.         public int getId() {
  6.           return id;
  7.          }

  8.     public void setId(int id) {
  9.         this.id = id;
  10.     }

  11. }
  12. ;

Object

  • Object is nothing but instance (dynamic memory allocation) of a class.
  • The dynamic memory allocated at run time for the members [non-static variables] of the class is known as object.

What is a Reference variable?

  • Reference variable is a variable which would be representing the address of the object.
  • Reference will act as a pointer and handler to the object.
  • Since reference variable always points an object.
  • In practice we call the reference variable also as an object.
  • We can create an object by using new operator.
  • If we want to call any method inside the class we need object
               Syntax: A obj= new A();

Example program:

      public class A {
         int a;
     public  void Print(){
        System.out.println("value of a="+a);
    }
    public static void main(String[] args) {
   A obj=new A();
  obj.print();
    }
}

Output: value of a=0
What Object Contains?
  • Object of any class contains only data.
  • Apart from the data object of a class would not contains anything else.
  • Object of a class would not contain any functionalities or logic.
  • Thus object of a class would be representing only data and not represent logic.

What is state of the Object?

  • The data present inside object of a class at that point of time is known as state of the object

What is behavior of the object? 

  • The functionalities associated with the object => Behavior of the object.
     The state of the object changes from time-to-time depending up on the functionaities that are executed on that object but whereas behavior of the object would not change.



Naming conventions for declaring a class:

  • Class name should be relevant.
  • Use UpperCamelCase for class names. //StudentDemoClass
  • For Methods names follow camelCase(); //getName();
  • Declare variables lowercase first letter. // int rollNumber
  • To declare final static variables means which will acts like constants
    MIN_WIDTH=10;
    MAX_AGE=18;

Check armstrong number or not


  1. package com.instanceofjavaTutorial; 
  2. import java.util.Scanner;

  3. public class ArmstrongNumber{
  4.  
  5. public static void main(String args[])
  6.  {
  7.  
  8.           int n, sum = 0, temp, r;
  9.  
  10.           Scanner in = new Scanner(System.in);
  11.  
  12.           System.out.println("Enter a number to check if it is an Armstrong number or not");     
  13.           n = in.nextInt();
  14.  
  15.           temp = n;
  16.           while( temp != 0 )
  17.           {
  18.  
  19.              r = temp%10;
  20.              sum = sum + r*r*r;
  21.              temp = temp/10; 
  22.  
  23.           }
  24.  
  25.           if ( n == sum )
  26.              System.out.println(n+"is an Armstrong number.");
  27.           else
  28.              System.out.println(n+"  is not an Armstrong number.");  
  29.        
  30.        }
  31. }


Output:

  1. Enter a number to check if it is an Armstrong number or not
  2. 153
  3. 153is an Armstrong number.



Constructor Overloading

  • Concept of defining multiple constructors within the same class by changing the data types of the parameters is known as constructor overloading.
package com.instanceofjavaforus;

public class ConstructorOverloading {

int a,b,c;

ConstructorOverloading(){
    this(1);
}

ConstructorOverloading(int a){
    this(a,2);
}

ConstructorOverloading(int a, int b){
    this(a,b,3);
}

ConstructorOverloading(int a, int b,int c){
this.a=1;
this.b=2;
this.c=3;
System.out.println(a+""+b+""+c);
}
   
public static void main(String args[]){
   
    ConstructorOverloading obj=new ConstructorOverloading();
   
   }
   
}


OutPut:
1 2 3
Select Menu