Saturday, October 26, 2013

Example program of geting data from user using Wrapper Class

In below program, we will convert instance variable into wrapper class!

If you want to get data from user, you must have to import the java class from library, you can do this by import weather "java.io", "java.util" or "java.scanner", you can use any one of this ! 


import java.io.*;

public class employee{

int empnumber;
String name;
String add;

private void getdata()throws IOException{

DataInputStream d = new DataInputStream(System.in);

System.out.println("Enter Employee Number: ");
empnumber= Integer.parseInt(d.readLine()); 

//here we convert integer into wrapper class


System.out.println("Enter Emplyee Name: ");
name = d.readLine(); 

//in both string value,we haven't convert because String is a class not variable so no need to convert in to wrapper class

System.out.println("Enter Employee Address: ");
add=d.readLine();
}

private void display()throws IOException {

System.out.println(empnumber+"\t"+name+"\t"+add);

}



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

employee e1 = new employee();
employee e2 = new employee();

e1.getdata();
e2.getdata();

e1.display();
e2.display();
}
}

Facts about Constructor with an example...............

Some facts that you should know about Constructor.....................


  • It has the same name as the classname.
  • It is used to initialize the object that means it is used to construct the object.
  • It does not have any return type.
  • It can have arguments.
  • The constructor without argument is called default constructor.
  • A class can have more than one constructor but they must be different from each other by  
     - Number of arguments or
     - Type of arguments or
     - Sequence of arguments
This concept is called constructor overloading.  

  • It is automatically called when an object is created.
Simple example to explain constructor in program.
___________________________________________


import java.io.*;
class cons
{
int a,b;
cons()//defulat constructer
{
a=10;
b=20;
System.out.println("default constructer");
}
cons(int p,int q)//parametrised constructer
{
a=p;
b=q;
System.out.println("parametrised constructer");
}
cons(int p)//one parametrised constructer
{
a=p;
b=25;
System.out.println("one parametrised constructer");
}
void show()
{
System.out.println("a = "+a);
System.out.println("b = "+b);
}

public static void main(String arg[])throws IOException
{
cons c1=new cons(); 
c1.show();
cons c2=new cons(10); 
c2.show();
cons c3=new cons(100,200); 
c3.show();
cons c4=new cons(); 
c4.show();
cons c5=new cons(); 
c5.show();
cons c6=new cons(1000,2000); 
c6.show();
cons c7=new cons(5000,10000); 
c7.show();
}
}