Thursday, February 20, 2014

Example of StringBuffer insert method in java.

public class StringBufferInsertMethod
{
public static void main(String surat[])
{
StringBuffer sb = new StringBuffer("Mahi CandyFry");
System.out.println(sb);

String str1 = "Hello ";
sb.insert(0, str1);
System.out.println(sb);

String str2 = " of ";
sb.insert(11, str2);
System.out.println(sb);
}
}

Output:

Example of StringBuffer delete method in java.

public class StringBufferDeleteCharacters
{
public static void main(String surat[])
{
StringBuffer sb = new StringBuffer("Mahi");
System.out.println("Original text: " + sb);

sb.delete(0, 2);
System.out.println("Current text: " + sb);

sb.deleteCharAt(sb.length()-1);
System.out.println("Current text: " + sb);
}
}

Output:


Example of StringBuffer reverse method in java.

public class StringBufferReverseMethod
{
public static void main(String surat[])
{
StringBuffer sb = new StringBuffer("Mahi CandyFry");
System.out.println("Original text: " + sb);

sb.reverse();
System.out.println("Reversed text: " + sb);
}
}

Output:



Example of StringBuffer replace method in java.

public class StringBufferReplaceMethod
{
public static void main(String surat[])
{
StringBuffer sb = new StringBuffer();
sb.append("CandyFry Developers");

System.out.println("Original Text : " + sb);

sb.replace(0, 8, "Hello");

System.out.println("Replaced Text : " + sb);
}
}

Output:


Example of StringBuffer append method.

public class StringBufferAppendMethod
{
    public static void main(String surat[])
{
        StringBuffer sb = new StringBuffer();

        sb.append(" Append String: ");
  String str = "JCG";
sb.append(str);

        sb.append("\n Append boolean: ");
boolean b = true;
sb.append(b);

        sb.append("\n Append char: ");
char c = 'a';
sb.append(c);

        sb.append("\n Append char array: ");
char[] ca = new char[] {'J','C','G'};
sb.append(ca);

        sb.append("\n Append double: ");
double d = 1.0;
sb.append(d);

        sb.append("\n Append float: ");
float f = 1.0f;
sb.append(f);

        sb.append("\n Append int: ");
int i = 1;
sb.append(i);
     
sb.append("\n Append Object: ");
  Object obj = new String("JCG");
        sb.append(obj);

        System.out.println(sb.toString());
    }
}

Output:


Monday, February 17, 2014

Java URL class.

import java.io.*;
import java.net.*;
 
public class URLDemo
{
public static void main(String surat[])
{
try
{
URL url=new URL("http://www.facebook.com");
 
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

Sunday, February 16, 2014

Serialization : ObjectInputStream :- Converting stream into object.

import java.io.Serializable;
import java.io.*;

class student implements Serializable
{
int id;
String name;

public student(int id,String name)
{
this.id=id;
this.name=name;
}
}

public class Serialisation1
{
public static void main(String surat[]) throws IOException
{
student s1=new student(1,"MaHi");

FileOutputStream fout=new FileOutputStream("m3.txt");

ObjectOutputStream out=new ObjectOutputStream(fout);

out.writeObject(s1);
out.flush();
System.out.println("Success");
}
}

Output:


Example of SequenceInputStream that reads data from multiple files using Enumeration.

SequenceInputStream2.java


import java.io.*;
import java.util.*;

class SequenceInputStream2
{
public static void main(String surat[])throws IOException
{
FileInputStream fin1=new FileInputStream("si1.java");
FileInputStream fin2=new FileInputStream("si2.txt");
FileInputStream fin3=new FileInputStream("si3.txt");
FileInputStream fin4=new FileInputStream("si4.java");

Vector v=new Vector();
v.add(fin1);
v.add(fin2);
v.add(fin3);
v.add(fin4);

Enumeration e=v.elements();

SequenceInputStream bin=new SequenceInputStream(e);

int i=0;
while((i=bin.read())!=-1)
{
System.out.println((char)i);
}

bin.close();
fin1.close();
fin2.close();
}
}

si1.java


class si1
{
public static void main(String surat[])
{
System.out.println("MaHi1");
}
}

si2.txt


Mahi2

si3.txt


Mahi3

si4.java


class si4
{
public static void main(String surat[])
{
System.out.println("MaHi1");
}
}

Java SequenceInputStream.

SequenceInputStream1.java


import java.io.*;
class SequenceInputStream1
{
public static void main(String surat[])throws IOException
{
FileInputStream fin1=new FileInputStream("m1.txt");
FileInputStream fin2=new FileInputStream("m2.txt");

SequenceInputStream sis=new SequenceInputStream(fin1,fin2);

int i;
while((i=sis.read())!=-1)
{
System.out.println((char)i);
}
}
}

m1.txt


Mahi1

m2.txt


Mahi2

Output:



Java PipedInputStream and PipedOutputStream.

import java.io.*;
class Poutput implements Runnable
{
PipedOutputStream pout;

Poutput(PipedOutputStream pout)
{
this.pout=pout;
}
public void run()
{
for(int i=65;i<91;i++)
{
try
{
pout.write(i);
Thread.sleep(500);
}
catch(Exception e){}
}
}
}
class Pinput implements Runnable
{
PipedInputStream pin;

Pinput(PipedInputStream pin)
{
this.pin=pin;
}
public void run()
{
int z=0;
for(int i=65;i<91;i++)
{
try
{
z=pin.read();
}
catch(Exception e){}
System.out.println((char)z);
}
}
}
class PipedInputStream1
{
public static void main(String surat[])throws IOException
{
PipedOutputStream pout=new PipedOutputStream();
PipedInputStream pin=new PipedInputStream();

pout.connect(pin);

Poutput po=new Poutput(pout);
Pinput pi=new Pinput(pin);

Thread t1=new Thread(po);
Thread t2=new Thread(pi);

t1.start();
t2.start();
}
}

Output:


Java Buffer

Buffer.java

import java.io.*;
class Buffer1
{
public static void main(String surat[])throws IOException
{
FileOutputStream fout=new FileOutputStream("mahi1.txt");
BufferedOutputStream bout=new BufferedOutputStream(fout);

String s="Good Morning";
byte b[]=s.getBytes();
bout.write(b);

bout.flush();
bout.close();

System.out.println("Success");
}
}

Output:


Friday, February 14, 2014

Simple program of reading data from the file using buffer.

bufferReader1.java

import java.io.*;

class bufferReader1
{
public static void main(String surat[]) throws IOException
{
FileInputStream f=new FileInputStream("mahi.txt");

BufferedInputStream b=new BufferedInputStream(f);

int i;
while((i=b.read())!=-1)
{
System.out.println((char)i);
}
f.close();
}
}

mahi.txt

Helloooo UI.

Output:


Tuesday, February 11, 2014

Suppose there are two values stored in the add.txt, read those integers from the file and display their sum on the console.

//Scanner2.java

import java.util.Scanner;
import java.io.*;

public class Scanner2
{
    public static void main(String surat[]) throws IOException
{
        Scanner s=new Scanner(new File("add.txt"));

        int n1=s.nextInt();
        int n2=s.nextInt();

        System.out.println(n1+n2);
    }
}

//add.txt

10
20

Output:


Example of addition using Swing JOptionPane.

import javax.swing.JOptionPane;

class SwingAddition
{
public static void main(String surat[])
{
String s1=JOptionPane.showInputDialog("Enter First Number");
String s2=JOptionPane.showInputDialog("Enter Second Number");

int n1=Integer.parseInt(s1);
int n2=Integer.parseInt(s2);

int sum=n1+n2;

JOptionPane.showMessageDialog(null,"The sum is " + sum,"Addition", JOptionPane.PLAIN_MESSAGE );
}
}

Output:

Another program of Addition of two numbers using Stream concept.

import java.io.*;

public class Asignment12
{
public static void main(String surat[]) throws IOException
{
DataInputStream d=new DataInputStream(System.in);

System.out.print("A: ");
int a =Integer.parseInt(d.readLine());

System.out.print("B: ");
int b = Integer.parseInt(d.readLine());

int c=a+b;
System.out.println("Addition : "+c);
}
}

Output:

Write a program of Addition of two numbers using Stream concept.

import java.io.*;
class Asignment12
{
public static void main(String surat[]) throws IOException
{
InputStreamReader i=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(i);

int a=0;
int b=0;
int c;

System.out.print("A: ");
a=Integer.parseInt(br.readLine());

System.out.print("B: ");
b=Integer.parseInt(br.readLine());

c=a+b;

System.out.println("Addition : "+c);
}
}

Output:

Example of DataInputStream and DataOutputStream.

import java.io.*;

class DataStream
{
public static void main(String surat[]) throws IOException
{
DataInputStream din=new DataInputStream(System.in);

FileOutputStream fout=new FileOutputStream("Mahi.txt");

DataOutputStream dout=new DataOutputStream(fout);

String s="";
while(!s.equals("stop"))
{
s=din.readLine();
System.out.println(s);
dout.writeBytes(s);
dout.flush();
}
din.close();
dout.close();
}
}

Output:

Example of Reading the data of current java file and writing it into another file.

import java.io.*;

class Asignment11
{
public static void main(String surat[])throws Exception
{

FileInputStream fin=new FileInputStream("mahi.txt");
FileOutputStream fout=new FileOutputStream("bhavna.txt");

int i=0;

while((i=fin.read())!=-1)
{
fout.write((byte)i);
}

fin.close();
}
}

Output:

Monday, February 10, 2014

Example of StringBuilder by ensureCapacity() method in java.

class string27
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity());//default 16

sb.append("Hello");
System.out.println(sb.capacity());//now 16

sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2

sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34

sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}

Output:

Example of StringBuilder by reverse() method in java.

class string26capacity
{
public static void main(String surat[])
{
StringBuilder sb=new StringBuilder();
System.out.println(sb.capacity()); //default 16

sb.append("Hello");
System.out.println(sb.capacity()); //now 16

sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Output:

Example of StringBuilder by reverse() method in java.

class string25reverse
{
public static void main(String surat[])
{
StringBuilder sb=new StringBuilder("Hello");

sb.reverse();

System.out.println(sb);//prints olleH
}
}

Output:

Example of StringBuilder by delete() method in java.

class string24
{
public static void main(String surat[])
{
StringBuilder sb=new StringBuilder("Hello");

sb.delete(1,3);

System.out.println(sb);//prints Hlo
}
}

Output:

Example of StringBuilder by replace() method in java.

class string23
{
public static void main(String surat[])
{
StringBuilder sb=new StringBuilder("Hello");

sb.replace(1,3,"Java");

System.out.println(sb);//prints HJavalo
}
}

Output:

Example of StringBuilder by insert() method in java.

class string22
{
public static void main(String surat[])
{
StringBuilder sb=new StringBuilder("Hello ");

sb.insert(1,"Java"); //now original string is changed

System.out.println(sb); //prints HJavaello
}
}

Output:

Example of StringBuilder by append method in java.

class string21
{
public static void main(String surat[])
{
StringBuilder sb=new StringBuilder("Hello ");

sb.append("Java"); //now original string is changed

System.out.println(sb); //prints Hello Java
}
}

Output:

Example of FileInputStream in java.

import java.io.*;

class MyFileReader
{
public static void main(String surat[]) throws IOException
{
FileInputStream fr=new FileInputStream("Temp.txt");
int i=0;

while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}

Output:

Example of FileOutputStream in java

import java.io.*;

class MyFileWriter
{
public static void main(String surat[])
{
try
{
FileOutputStream fw=new FileOutputStream("Temp.txt");

String s="Good Day";

byte ch[]=s.getBytes();

fw.write(ch);
fw.close();
}
catch(Exception e){}
}
}

Output:

Saturday, February 8, 2014

Example of JSlider in java.

import javax.swing.*;

public class mahi extends JFrame
{
    public mahi()
{
        setTitle("JSlider");
        setSize(300,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JSlider s=new JSlider(JSlider.HORIZONTAL);
        add(s);
        setVisible(true);
    }
    public static void main(String surat[])
{
new mahi();
    }
}

Output:

Monday, February 3, 2014

Simple example of Graphic in java.

import java.awt.*;
import javax.swing.*;

public class displayGraphic extends Canvas
{
    public void paint(Graphics g)
    {
        setBackground(Color.white);
        setForeground(Color.red);
       
        g.drawString("Hello",40,40);
        g.fillRect(130,30,100,80);
        g.drawOval(30,130,50,60);
        g.fillOval(130,130,50,60);
        g.drawArc(30,200,40,50,90,60);
        g.fillArc(30,130,40,50,180,40);
    }
    public static void main(String surat[])
    {
        displayGraphic m=new displayGraphic();
        JFrame f=new JFrame();
        f.add(m);
        f.setSize(300,300);
        f.setVisible(true);
    }
}

Output:

Another example of JTree.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

class MyTree
{
    JFrame f;
    JTree t;
    JScrollPane p;
   
    MyTree()
    {
        f=new JFrame("JTree Demo");
       
        DefaultMutableTreeNode root=new DefaultMutableTreeNode("Style");
       
        DefaultMutableTreeNode color=new DefaultMutableTreeNode("Color");
       
        DefaultMutableTreeNode font=new DefaultMutableTreeNode("Font");
       
        root.add(color);
        root.add(font);
       
        DefaultMutableTreeNode red=new DefaultMutableTreeNode("Red");
        DefaultMutableTreeNode green=new DefaultMutableTreeNode("Green");
        DefaultMutableTreeNode blue=new DefaultMutableTreeNode("Blue");
       
        color.add(red);
        color.add(green);
        color.add(blue);
       
        DefaultMutableTreeNode bold=new DefaultMutableTreeNode("Bold");
        DefaultMutableTreeNode italic=new DefaultMutableTreeNode("Italic");
        DefaultMutableTreeNode underline=new DefaultMutableTreeNode("Underline");
       
        font.add(bold);
        font.add(italic);
        font.add(underline);
       
        t=new JTree(root);
       
        p=new JScrollPane(t);
        f.add(p);
       
        f.setSize(350,350);
        f.setVisible(true);
    }
    public static void main(String surat[])
    {
        new MyTree();
    }
}

Output:

Another example of JFileChooser

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class filechooser extends JFrame implements ActionListener
{
    JFileChooser jfc;
   
    public filechooser()
    {
        super("File Chooser");
        jfc=new JFileChooser("e:/");
        JButton jb=new JButton("Ok");
        jb.addActionListener(this);
        getContentPane().add(jb);
        setLayout(new FlowLayout());
        setSize(300,300);
        setVisible(true);
    }
   
    public void actionPerformed(ActionEvent e)
    {
        int x=jfc.showOpenDialog(null);
       
        if(x==JFileChooser.APPROVE_OPTION)
        {
            File f=jfc.getSelectedFile();
            String s=jfc.getName(f);
            System.out.println(s);
        }
       
        if(x==JFileChooser.CANCEL_OPTION)
        {
            System.out.println("Cancel");
        }
    }
    public static void main(String surat[])
    {
        new filechooser();
    }
}

Output:

Example of JTree.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

public class JTreeDemo
{
    public static void main(String surat[])
    {
        new JTreeDemo();
    }

    public JTreeDemo()
    {
        JFrame f = new JFrame("JTree Demo");
        Container c = f.getContentPane();
        c.setLayout( new BorderLayout() );

        //Create top node of a tree
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Course");

        //Create a subtree
        DefaultMutableTreeNode UG = new DefaultMutableTreeNode("Bachelor");
        top.add(UG);

        DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("B.E");
        UG.add(a1);
        DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("B.C.A");
        UG.add(a2);
        DefaultMutableTreeNode a3 = new DefaultMutableTreeNode("B.Sc");
        UG.add(a3);
        DefaultMutableTreeNode a4 = new DefaultMutableTreeNode("B.Com");
        UG.add(a4);
        DefaultMutableTreeNode a5 = new DefaultMutableTreeNode("B.A");
        UG.add(a5);

        //Create a subtree
        DefaultMutableTreeNode PG = new DefaultMutableTreeNode("Master");
        top.add(PG);

        DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("M.E");
        PG.add(b1);
        DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("M.C.A");
        PG.add(b2);
        DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("M.Sc");
        PG.add(b3);
        DefaultMutableTreeNode b4 = new DefaultMutableTreeNode("M.Com");
        PG.add(b4);
        DefaultMutableTreeNode b5 = new DefaultMutableTreeNode("M.A");
        PG.add(b5);

        //Creating tree
        final JTree tree = new JTree(top);//it is accessed within inner class so it must be final

        int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
        int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
        JScrollPane jsp = new JScrollPane(tree,v,h);
        c.add(jsp,BorderLayout.CENTER );

        final JTextField text = new JTextField("",20);//it is accessed within inner class so it must be final
        c.add(text,BorderLayout.SOUTH);

        tree.addMouseListener( new MouseAdapter()
        {
            public void mouseClicked( MouseEvent me)
            {
                TreePath tp = tree.getPathForLocation(me.getX(),me.getY() );
               
                if( tp != null )
                    text.setText(tp.toString() );
                else
                    text.setText("");
            }
        });

        f.setSize(300,300);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Output:

Example of JFileChooser in java.

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class JFileChooserTest implements ActionListener
{
    JFileChooserTest()
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);
        JFrame f = new JFrame("JFileChooser Test");
        f.setLayout(new FlowLayout());
       
        JButton b = new JButton("Select File");
        b.addActionListener(this);
        f.add(b);
       
        f.setSize(300,300);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent ae)
    {
        JFileChooser fc = new JFileChooser();
        int returnValue = fc.showOpenDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION)
        {
            File selectedFile = fc.getSelectedFile();
            System.out.println(selectedFile.getName());
        }
    }
    public static void main(String surat[])
    {
        new JFileChooserTest();
    }
}

Output:

JFileChooser Dialog box example2

import javax.swing.*;

class fileChooser2
{
    JFrame f;
   
    fileChooser2()
    {
        f=new JFrame();
        JFileChooser fc=new JFileChooser();
        f.add(fc);
        f.setVisible(true);
        f.setSize(450,350);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    }
    public static void main(String surat[])
    {
        new fileChooser2();
    }
}

Output:

JFileChooser Dialog box program.

import javax.swing.*;

public class fileChooser1 extends JFrame
{
    public fileChooser1()
    {
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Choose a file");
        this.getContentPane().add(fc);
        fc.setVisible(true);
    }
    public static void main(String surat[])
    {
        JFrame f = new fileChooser1();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
}

Output:

Digital watch program in java.

import javax.swing.*;
import java.awt.*;
import java.text.*;
import java.util.*;

public class DigitalWatch implements Runnable

    JFrame f; 
    Thread t=null;
    int hours=0, minutes=0, seconds=0;
    String timeString = "";
    JButton b;

    DigitalWatch()
    { 
        f=new JFrame();
     
        t = new Thread(this);
        t.start();
     
        b=new JButton();
     
        f.add(b);
        f.setSize(300,300);
        f.setLayout(new CardLayout());
        f.setVisible(true);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    }

    public void run()
    { 
        try
        { 
            while (true)
            { 
                Calendar cal=Calendar.getInstance();
                hours=cal.get(Calendar.HOUR_OF_DAY);
                if(hours>12)hours-=12;
                    minutes = cal.get(Calendar.MINUTE);
                    seconds = cal.get(Calendar.SECOND);

                SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
                Date date = cal.getTime();
                timeString = formatter.format(date);
               
                b.setText(timeString);

                t.sleep( 1000 );
            }
        }
        catch(Exception e){}
    }

    public static void main(String surat[])
    {
        new DigitalWatch();
    }
}

Output:

Example of JTabel in java

import javax.swing.*;

public class MyTable
{
    JFrame f;

    MyTable()
    {
        f=new JFrame("JTabel");

        String data[][]={
                            {"1","Mahi","900000"}, 
                            {"2","Pari","500000"}, 
                            {"3","Bhavna","720000"}
                        };
   
        String column[]={"ID","NAME","SALARY"};
     
        JTable jt=new JTable(data,column);
        jt.setBounds(30,40,200,300);
     
        JScrollPane sp=new JScrollPane(jt);
        f.add(sp);

        f.setSize(400,200);
        f.setVisible(true);
    }

    public static void main(String surat[])
    { 
        new MyTable(); 
    }
}

Output:

2 Value Addtion in java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Event4Addition implements ActionListener
{
    JFrame f;
    JLabel l1,l2,l3;
    JTextField t1,t2,t3;
    JButton b1,b2;
   
    Event4Addition(String s)
    {
        f=new JFrame(s);
        f.setLayout(new GridLayout(4,2));
       
        l1=new JLabel("Number1:",JLabel.CENTER);
        f.add(l1);
       
        t1=new JTextField();
        t1.setHorizontalAlignment(JTextField.CENTER);
        f.add(t1);
       
        l2=new JLabel("Number2:",JLabel.CENTER);
        f.add(l2);
       
        t2=new JTextField();
        t2.setHorizontalAlignment(JTextField.CENTER);
        f.add(t2);
       
        l3=new JLabel("Answer:",JLabel.CENTER);
        f.add(l3);
       
        t3=new JTextField();
        t3.setHorizontalAlignment(JTextField.CENTER);
        t3.setEditable(false);
        f.add(t3);
       
        b1=new JButton("Add");
        b2=new JButton("Clear");
        f.add(b1);
        f.add(b2);
       
        b1.addActionListener(this);
        b2.addActionListener(this);
       
        f.setSize(455,220);
        f.setVisible(true);
        f.setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        float a,b,c;
        if(e.getSource()==b1)
        {
            a=Float.parseFloat(t1.getText());
            b=Float.parseFloat(t2.getText());
            c=a+b;
            t3.setText(Float.toString(c));
        }
        else
        {
            t1.setText(null);
            t2.setText(null);
            t3.setText(null);
        }
    }
    public static void main(String surat[])
    {
        new Event4Addition("Addition");
    }
}

Output: