Sunday, October 16, 2011

Java Arithmatic Operation without Operator



ArithmeticOperation.java
import java.awt.EventQueue;
import java.math.BigDecimal;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ArithmeticOperation extends JFrame {

    private JPanel contentPane;
    private JTextField text_fno;
    private JTextField text_sno;
    private JTextField text_ans;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ArithmeticOperation frame = new ArithmeticOperation();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public ArithmeticOperation() {
        setTitle("Arithmetic Opertion");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 520, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
       
        JPanel panel_arithmetic = new JPanel();
        panel_arithmetic.setBounds(40, 24, 417, 227);
        contentPane.add(panel_arithmetic);
       
        JLabel lblEnterNo = new JLabel("Enter No :-");
        lblEnterNo.setBounds(10, 29, 61, 14);
        lblEnterNo.setHorizontalAlignment(SwingConstants.RIGHT);
       
        JLabel label = new JLabel("Enter No :-");
        label.setBounds(10, 81, 61, 14);
        label.setHorizontalAlignment(SwingConstants.RIGHT);
       
        text_fno = new JTextField();
        text_fno.setBounds(75, 26, 86, 20);
        text_fno.setColumns(10);
       
        text_sno = new JTextField();
        text_sno.setBounds(75, 78, 86, 20);
        text_sno.setColumns(10);
       
        text_ans = new JTextField();
        text_ans.setBounds(75, 125, 86, 20);
        text_ans.setColumns(10);
       
        JLabel lblAnswer = new JLabel("Answer :-");
        lblAnswer.setBounds(10, 128, 61, 14);
        lblAnswer.setHorizontalAlignment(SwingConstants.RIGHT);
       
        JButton btnAdditon = new JButton("Additon");
        btnAdditon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                BigDecimal fno=new BigDecimal(text_fno.getText());
                BigDecimal sno=new BigDecimal(text_sno.getText());
               
                try
                {
                    BigDecimal ans=addition(fno, sno);
                    text_ans.setText(ans.toString());
                } catch (Exception e2) {
                    // TODO: handle exception
                    JOptionPane.showMessageDialog(contentPane, "Error In Arithmetic Operation","Error",JOptionPane.ERROR_MESSAGE);
                }
               
               
            }
        });
        btnAdditon.setBounds(216, 25, 115, 23);
       
        JButton btnSubstraction = new JButton("Substraction");
        btnSubstraction.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {
                BigDecimal fno=new BigDecimal(text_fno.getText());
                BigDecimal sno=new BigDecimal(text_sno.getText());
               
                try
                {
                    BigDecimal ans=substraction(fno, sno);
                    text_ans.setText(ans.toString());
                } catch (Exception e2) {
                    // TODO: handle exception
                    JOptionPane.showMessageDialog(contentPane, "Error In Arithmetic Operation","Error",JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        btnSubstraction.setBounds(216, 59, 115, 23);
       
        JButton btnMutltiplication = new JButton("Mutltiplication");
        btnMutltiplication.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {

                BigDecimal fno=new BigDecimal(text_fno.getText());
                BigDecimal sno=new BigDecimal(text_sno.getText());
               
                try
                {
                    BigDecimal ans=multiplication(fno, sno);
                    text_ans.setText(ans.toString());
                } catch (Exception e2) {
                    // TODO: handle exception
                    JOptionPane.showMessageDialog(contentPane, "Error In Arithmetic Operation","Error",JOptionPane.ERROR_MESSAGE);
                }
           
            }
        });
        btnMutltiplication.setBounds(216, 93, 115, 23);
       
        JButton btnDivison = new JButton("Divison");
        btnDivison.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e)
            {


                BigDecimal fno=new BigDecimal(text_fno.getText());
                BigDecimal sno=new BigDecimal(text_sno.getText());
               
                try
                {
                    BigDecimal ans=division(fno, sno);
                    text_ans.setText(ans.toString());
                }
                catch (ArithmeticException e2)
                {
                    // TODO: handle exception
                    JOptionPane.showMessageDialog(contentPane, "Error In Arithmetic Operation","Error",JOptionPane.ERROR_MESSAGE);
                }
                catch (Exception e2) {
                    // TODO: handle exception
                    JOptionPane.showMessageDialog(contentPane, "Error In Arithmetic Operation","Error",JOptionPane.ERROR_MESSAGE);
                }
           
           
            }
        });
        btnDivison.setBounds(216, 128, 115, 23);
        panel_arithmetic.setLayout(null);
        panel_arithmetic.add(lblEnterNo);
        panel_arithmetic.add(text_fno);
        panel_arithmetic.add(btnAdditon);
        panel_arithmetic.add(label);
        panel_arithmetic.add(text_sno);
        panel_arithmetic.add(btnSubstraction);
        panel_arithmetic.add(btnDivison);
        panel_arithmetic.add(lblAnswer);
        panel_arithmetic.add(text_ans);
        panel_arithmetic.add(btnMutltiplication);
    }
   
    public BigDecimal addition(BigDecimal fno,BigDecimal sno)
    {
        return fno.add(sno);
    }
   
    public BigDecimal substraction(BigDecimal fno,BigDecimal sno)
    {
        return fno.subtract(sno);
    }
   
    public BigDecimal multiplication(BigDecimal fno,BigDecimal sno)
    {
        return fno.multiply(sno);
    }
    public BigDecimal division(BigDecimal fno,BigDecimal sno)
    {
        return fno.divide(sno);
    }
}

Friday, October 14, 2011

Java Google Translator Using Swing


MyTranslator.java
import java.awt.EventQueue;
import java.lang.reflect.Field;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class MyTranslator extends JFrame {

private JPanel contentPane;
JComboBox combo_from;
JComboBox combo_to;
Class myClass;
private JLabel lblTo;
JTextArea text_to;


JTextArea text_from;
private JLabel lblLanguage;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try
{
MyTranslator frame = new MyTranslator();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
* @throws ClassNotFoundException
*/
public MyTranslator() throws ClassNotFoundException
{
Translate.setHttpReferrer("translate.google.com");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 487, 261);
contentPane = new JPanel();

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
this.setTitle("Google Translator..");
combo_to= new JComboBox();
combo_from= new JComboBox();

//load language class for language list
myClass=Class.forName("com.google.api.translate.Language");
Field[] f=myClass.getFields();combo_to.addItem("--Select--");
combo_from.addItem("--Select--");
for (int i = 0; i < f.length; i++) { combo_to.addItem(f[i].getName()); combo_from.addItem(f[i].getName()); } lblTo = new JLabel("TO"); text_to= new JTextArea(); JButton btn_translate = new JButton("TRANSLATE"); btn_translate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { String translation=Translate.execute(text_to.getText(),Language.valueOf(combo_to.getSelectedItem().toString()),Language.valueOf(combo_from.getSelectedItem().toString())); text_from.setText(translation); } catch (Exception e1) { // TODO Auto-generated catch block //e1.printStackTrace(); JOptionPane.showMessageDialog(contentPane,"Error In Language Translation...","Error",JOptionPane.ERROR_MESSAGE); //JOptionPane.showMessageDialog(, message, title, messageType) } } }); text_from= new JTextArea(); lblLanguage = new JLabel("Language :-"); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addContainerGap() .addComponent(lblLanguage) .addGap(24) .addComponent(combo_to, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(lblTo)) .addGroup(gl_contentPane.createSequentialGroup() .addGap(20) .addComponent(text_to, GroupLayout.PREFERRED_SIZE, 187, GroupLayout.PREFERRED_SIZE))) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(14) .addComponent(combo_from, GroupLayout.PREFERRED_SIZE, 91, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(btn_translate)) .addGroup(gl_contentPane.createSequentialGroup() .addGap(30) .addComponent(text_from, GroupLayout.PREFERRED_SIZE, 179, GroupLayout.PREFERRED_SIZE))) .addGap(32)) ); gl_contentPane.setVerticalGroup( gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(12) .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE) .addComponent(combo_to, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblTo) .addComponent(combo_from, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(btn_translate) .addComponent(lblLanguage)) .addGap(37) .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addGap(5) .addComponent(text_from, GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)) .addComponent(text_to, GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)) .addContainerGap()) ); contentPane.setLayout(gl_contentPane); } }



Note :- This Program Required google-api-translate-java-0.95.jar but some language translation are not possible...

Monday, October 10, 2011

OOP Concept in Java

Definition of Class: - Classes are the fundamental building blocks of a Java program. which contain the data member and member function

Definition of Object:- Objects are key to understanding object-oriented technology. object are connect to the real world. every object have to characteristic. they have state and behavior. An object stores its state in fields and exposes its behavior through methods (Object are the instance of the class)

Definition of Inheritance:- inheritance is the process by which object of  one class  acquire the property of object of another class.

Definition of Polymorphism:- polymorphism means ability to take more than in one form.

Definition of Encapsulation:- The Wrapping up of data and method into the single unit is known as encapsulation.

Definition of Abstraction:- Abstraction in Java allows the user to hide non-essential details relevant to user. It allows only to show the essential features of the object to the end user.

Friday, September 23, 2011

Java Socket DayTime Service

DayTimeServer.java

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;


public class DayTimeServer
{

    ServerSocket serverSocket;
    Socket clientSocket;
    DataOutputStream dos;


    public DayTimeServer()
    {
        try
        {
            serverSocket = new ServerSocket(13);
            while(true)
            {
                System.out.print("Time Server Start....");
                clientSocket=serverSocket.accept();
                dos=new DataOutputStream(clientSocket.getOutputStream());
                Date date=new Date();
                dos.writeUTF(date.toString());
            }
           
        }
        catch (IOException ex)
        {
            Logger.getLogger(DayTimeServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static  void  main(String args[])
    {
        new DayTimeServer();
    }
}

DayTimeClient.java

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DayTimeClient
{
    Socket dtSocket;
    DataInputStream dis;

    public DayTimeClient()
    {
        try
        {
           
            dtSocket = new Socket("localhost", 13);
            dis=new DataInputStream(dtSocket.getInputStream());
            System.out.print("-: Day And Time :-\n"+dis.readUTF()+"\n");
        }
        catch (UnknownHostException ex) {
            Logger.getLogger(DayTimeClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DayTimeClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public static  void  main(String args[])
    {
        new DayTimeClient();
    }
}

How To Run :
Fisrst Start DayTimeServer.java
Second Start DayTimeClient.java

Sunday, September 11, 2011

Serialization In Java

What is Serialization?
 Serializable is a marker interface. When an object has to be transferred over a network ( typically through rmi or EJB) or persist the state of an object to a file, the object Class needs to implement Serializable interface. Implementing this interface will allow the object converted into bytestream and transfer over a network
 
What is the need of Serialization?
The serialization is used :-
  • To send state of one or more object’s state over the network through a socket.
  • To save the state of an object in a file.
  • An object’s state needs to be manipulated as a stream of bytes.

What is use of serialVersionUID ?
During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:
  • Add fields
  • Change a field from static to non-static
  • Change a field from transient to non-transient
  • Add classes to the object tree
List of incompatible changes:
  • Delete fields
  • Change class hierarchy
  • Change non-static to static
  • Change non-transient to transient
  • Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly metion the suid using the statement:

private final static long serialVersionUID = <integer value>


then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Are the static variables saved as the part of serialization?
No. The static variables belong to the class and not to an object they are not the part of the state of the object so they are not saved as the part of serialized object.

What is a transient variable?
These variables are not included in the process of serialization and are not the part of the object’s serialized state.

step 1. Implement The java.io.Serializable Interface
DocumentBean .java
import java.util.Date;

public class DocumentBean implements java.io.Serializable
{
    String docTitle;
    String date;
    int noOfPage;
    String docSize;   
   
    public DocumentBean(String docTitle,String data,int noOfPage,String docSize)
    {
        // TODO Auto-generated constructor stub
        this.docTitle=docTitle;
        this.date=data;
        this.noOfPage=noOfPage;
        this.docSize=docSize;
       
    }
    public String getDocTitle() {
        return docTitle;
    }
    public void setDocTitle(String docTitle) {
        this.docTitle = docTitle;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public int getNoOfPage() {
        return noOfPage;
    }
    public void setNoOfPage(int noOfPage) {
        this.noOfPage = noOfPage;
    }
    public String getDocSize() {
        return docSize;
    }
    public void setDocSize(String docSize) {
        this.docSize = docSize;
    }   
}
step 2 : Serialize The Object using ObjectOutputStream SerializeDocument.java

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

public class SerializeDocument
{   
    public static void main(String[] args)
    {       
        Date dt=new Date();
        DocumentBean bean=new DocumentBean("Java The Complate Refereance",dt.toString(),5,"A4");
        try
        {
            FileOutputStream fos=new FileOutputStream("Doc.txt");
            ObjectOutputStream oos=new ObjectOutputStream(fos);
            oos.writeObject(bean);
            System.out.println("Complate...");
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
step 3 : DeSerialize The Object using ObjectInputStream DeSerializeDocument.java

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeSerializeDocument
{
    public static void main(String[] args)
    {
        try
        {
            FileInputStream fis=new FileInputStream("Doc.txt");
            ObjectInputStream ois=new ObjectInputStream(fis);
            DocumentBean bean=(DocumentBean)ois.readObject();
            System.out.println("Doc Titel :"+bean.getDocTitle());
            System.out.println("Doc Page :"+bean.getNoOfPage());
            System.out.println("Doc Size :"+bean.getDocSize());
            System.out.println("Doc Date :"+bean.getDate());           
           
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
}