T.Y.B.B.A.(C.A.) Semester - VI University Practical Examination. Adv Java Programming Solved Slips

 

                                          Slip 1_1:-                

 

1. Write a java program to display IP Address and Name of client machine.                        [15]

 

c_slip1_1.java

 

import java.io.*;

import java.net.*;

class c_slip1_1

{

public static void main(String a[])throws Exception

{

Socket ss=new Socket("localhost",1000);

System.out.println("IP Address=" +ss.getInetAddress());

System.out.println("client port=" +ss.getPort());

}

}

 

s_slip1_1.java

 

import java.io.*;

import java.net.*;

class s_slip1_1

{

public static void main(String a[])throws Exception

{

ServerSocket ss=new ServerSocket(1000);

System.out.println("server is waiting for client:");

Socket s=ss.accept();

System.out.println("client is connected");

}

}

 

Output:-

 

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac s_slip1_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java s_slip1_1

server is waiting for client:

client is connected

 

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac c_slip1_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java c_slip1_1

IP Address=localhost/127.0.0.1

client port=1000

 

 

                                            Slip 2_1                 

 

Q1. Write a multithreading program in java to display all the vowels from a given String.(Use Thread Class)                                                                                                     [15]

 

 

importjava.util.*;

import java .io.*;

class slip2_1 extends Thread

{

  String s1;

   slip2_1(String s)

    {

      s1=s;

start();

    }

public void run( )

{

System.out.println("Vowels are  ");

for(int i=0;i<s1.length( );i++)

{

charch=s1.charAt(i);

if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u')

System.out.println(" "+ch);

}

}

public static void main(String a[ ]) throws Exception

{

BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter a string:-");

String str=br.readLine( );

slip2_1 v=new slip2_1(str);

}

}

Output:

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip2_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip2_1

Enter a string:-

admin

Vowels are

a

i

 

Slip 3                

 

Q1. Write a JDBC program to displays the details of employees (eno, ename, department, sal) whose department is “Computer Science”.                                                    [15]

 

importjava.sql.*;

import java.io.*;

class slip3_1

{

public static void main(String args[ ])

{

Connection con;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

 

con=DriverManager.getConnection("jdbc:odbc:mydb");

 

Statement stmt=con.createStatement( );

ResultSetrs=stmt.executeQuery("Select * From employee where department like 'computer science%' ");

System.out.println("eno\t"+"ename\t"+"department\t"+"sal");

while(rs.next( ))

{

System.out.println("\n"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));

}

 

rs.close( );

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

 

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip3_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip3_1

enoename   department      sal

 

1       raja    computer science        52000

 

Q 2. Write a java program to simulate traffic signal using multithreading.

         

import java.awt.*;

import java.applet.*;

public class slip3_2 extends java.applet.Applet implements Runnable

{

      int r,g1,y,i;

      Thread t;

      public void init()

      {

        r=0;g1=0;y=0;

        t=new Thread(this);

       t.start();

       }

    public void run()

    {

          try

             {

                  for (i=24;i>=1;i--)

                     {

                        t.sleep(100);

                        if (i>=16 && i<24)

                        {

                            g1=1;

                            repaint();

                         }

                        if (i>=8 && i<16)

                        {

                           y=1;

                           repaint();

                        }

                        if (i>=1 && i<8)

                        {

                            r=1;

                            repaint();

                        }

                     }

               if (i==0)

                  {

                    run();

                   }

            }

 

     catch(Exception e) {}

  }

 

public void paint(Graphics g)

 {

g.drawOval(100,100,100,100);

g.drawOval(100,225,100,100);

g.drawOval(100,350,100,100);

 

if (r==1)

       {   

           g.setColor(Color.red);

           g.fillOval(100,100,100,100);

           g.drawOval(100,100,100,100);

           r=0;

       }

if (g1==1)

       {      

         g.setColor(Color.green);

         g.fillOval(100,225,100,100);

         g1=0;

         g.drawOval(100,225,100,100);  

        

       }

if (y==1)

       {

       g.setColor(Color.yellow);

       g.fillOval(100,350,100,100);

       y=0;

       g.drawOval(100,350,100,100);

      

      }

  }

}

 

 

 

Output:-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip3_2.java

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Slip 4_1                 

 

Q1. Write a java program to display “Hello Java” message n times on the screen. (Use Runnable Interface).                                                                                          [15]

 

 

 

import java.io.*;

public class slip4 implements Runnable

{

inti,no;

slip4(int n)

  {

no=n;

  }

public void run( )

 {

for(i=1;i<no;i++)

     {

System.out.println("\n Hello Java");

try

        {

Thread.sleep(50);

         }

catch(Exception e)

        {

System.out.println(e);

         }

      }

 }

 

public static void main(String a[ ]) throws Exception

{

try

{

int n;

BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter a number:-");

String s=br.readLine( );

n=Integer.parseInt(s);

Thread t=new Thread(new slip4(n));

t.start( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output:

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip4.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip4

Enter a number:-

5

 

 Hello Java

 

 Hello Java

 

 Hello Java

 

 Hello Java

 

 

 

                                        Slip 5_1

Q1. Write a java program to create Teacher table(TNo.TName, Sal, Desg) and insert a record in it.     

import java.io.*;

importjava.sql.*;

class slip5_n

{

public static void main(String args[ ])

{

Connection con;

Statement stmt;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydb");

if(con==null)

{

System.out.println("Connection failed");

System.exit(1);

}

System.out.println("Connection Established.....");

stmt=con.createStatement( );

String query="create table Teacher "+"(Tnoint ,Tnamevarchar(20),salint,Desgvarchar(20))";

stmt.executeUpdate(query);

System.out.println("Teacher Table is created.....in database");

stmt.executeUpdate("insert into Teacher "+"values(1,'abc',2000,'mba')");

stmt.executeUpdate("insert into Teacher "+"values(2,'weewe',2000,'mba')");

stmt.executeUpdate("insert into Teacher "+"values(3,'errw',2000,'mba')");

stmt.executeUpdate("insert into Teacher "+"values(4,'ggd',2000,'mba')");

System.out.println("Successfully inserted in Database");

ResultSetrs=stmt.executeQuery("select * from Teacher");

System.out.println("Tno\t"+"Tname\t"+"sal\t"+"Desg");

while(rs.next( ))

{

System.out.println("\n"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3)+"\t"+rs.getString(4));

}

rs.close( );

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output :-

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip5_n.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip5_n

Connection Established.....

Teacher Table is created.....in database

Successfully inserted in Database

TnoTnamesalDesg

 

1       abc     2000    mba

 

2       weewe   2000    mba

 

3       errw    2000    mba

 

4       ggd     2000    mba

 

 

                                                              Slip 6

 

Q1. Write a JDBC program to accept the details of customer (CID, CName, Address, Ph_No) and store it into the database (Use PreparedStatement interface)

                                                                                                                   [15]

 

import java.io.*;

import java.sql.*;

class sl6_1

{

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

{

try

{

Connection con;

Statement stmt;

PreparedStatement ps;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

System.out.println("Connection Established.....11111");

stmt=con.createStatement( );

ps=con.prepareStatement("insert into cust values(?,?,?,?)");

System.out.println("Enter Cid:-");

int cid=Integer.parseInt(br.readLine( ));

ps.setInt(1,cid);

System.out.println("Enter Cname:-");

String cname=br.readLine( );

ps.setString(2,cname);

System.out.println("Enter add:-");

String add=br.readLine( );

ps.setString(3,add);

System.out.println("Enter PHNO:-");

int phno=Integer.parseInt(br.readLine( ));

ps.setInt(4,phno);

ps.executeUpdate( );

System.out.println("Record Inserted......!!!!!!!");

ResultSet rs=stmt.executeQuery("select * from cust");

while(rs.next( ))

{

System.out.println("\n"+rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getInt(4));

}

rs.close( );

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac sl6_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java sl6_1

Connection Established.....11111

Enter Cid:-

4

Enter Cname:-

smita

Enter add:-

lonikand

Enter PHNO:-

877474747

Record Inserted......!!!!!!!

 

1 miss.abc pune 234566666

 

2 sdgh aswe 23445

 

3 sneha pune 1234567654

 

4 smita lonikand 877474747

 

 

 

 

 

                                                   Slip 8_1                 

Q1. Write a Multithreading program using Runnable interface to blink Text on the frame.                                                                                                                  [15]

 

 

importjava.awt.*;

importjava.awt.event.*;

class slip8_1 extends Frame implements Runnable

{

 Thread t;

Label l1;

int f;

slip8_1( )

{

 t=new Thread(this);

t.start( );

setLayout(null);

l1=new Label("Hello Java");

l1.setBounds(100,100,100,40);

add(l1);

setSize(300,300);

setVisible(true);

f=0;

}

public void run( )

{

try

{

if(f==0)

{

t.sleep(200);

l1.setText(" ");

f=1;

}

if(f==1)

{

t.sleep(200);

l1.setText("hello java");

f=0;

}

}

catch(Exception e)

{

System.out.println(e);

}

run( );

}

public static void main(String a[ ])

{

new slip8_1( );

}

}

 

 

 

 

 

 

 

 

Output

 

 

 

 

 

 

 

                                     Slip9_1

Q1.  Write a JDBC program to delete the records of employees whose names are starting with ‘A’ character.

 

importjava.sql.*;

public class slip9_1

{

public static void main(String args[ ])

{

Connection con;

Statement stmt;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

 

con=DriverManager.getConnection("jdbc:odbc:mydb");

if(con==null)

{

System.out.println("Connection Failed");

System.exit(1);

}

System.out.println("Connection Established");

stmt=con.createStatement( );

int no=stmt.executeUpdate("Delete From employee where ename like 'A%' ");

if(no!=0)

System.out.println("Delete data successfully");

else

System.out.println("data not deleted");

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip9_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip9_1

Connection Established

Delete data successfully

 

Slip -10

Q1.  Write a JDBC program to count the number of records in table. (Without using standard method)                                                                                              [15]

 

import java.io.*;

importjava.sql.*;

class slip10

{

public static void main(String args[ ])

{

Connection con;

 

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydb");

if(con==null)

{

System.out.println("Connection failed");

System.exit(1);

}

System.out.println("Connection Established.....");

Statement stmt=con.createStatement( );

ResultSetrs=stmt.executeQuery("select * from Teacher");

intcnt=0;

while(rs.next( ))

{

cnt++;

}

System.out.println("Number of Records are :-"+cnt);

 

}

catch(Exception e)

{

System.out.println(e);

}

}

}

Output:-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip10.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip10

Connection Established.....

Number of Records are :-4

 

                                                            Slip 11

Q1. Write a JDBC program to remove “percentage” column from student (rno, sname, percentage) table.                                                                                                                   [15]

 

import java.io.*;

import java.sql.*;

class sl11_1

 

{

 

public static void main(String args[ ])

 

{

 

Try

 

{

 

Connection con;

Statement stmt;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

System.out.println("Connection Established");

stmt=con.createStatement( );

int no=stmt.executeUpdate("alter table cust drop Ph_No");

if(no>0)

 

{

 

System.out.println("not updated");

 

}

 

Else

 

{

System.out.println("table updated successfully");

}

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac sl11_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java sl11_1

Connection Established

table updated successfully

 

 

 

 

 

 

 

 

 

 

 

 

      Slip13_1

Q1. Write a JDBC program to create a Mobile (Model_No, Company_Name, Price, Color) table and insert a  record in it.                                                                                   [15]

 

import java.io.*;

importjava.sql.*;

importjava.util.*;

class slip13_1

{

public static void main(String args[ ])

{

Connection con;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydb");

if(con==null)

{

System.out.println("Connection Failed");

System.exit(1);

}

System.out.println("Connection Established");

Statement stmt=con.createStatement( );

String query="create table Mobile2 "+" (Model_Noint,"+"Company_Namevarchar(20),"+"Price int,"+"Color varchar(20))";

 

stmt.executeUpdate(query);

System.out.println("Table Created Successfully");

stmt.executeUpdate("insert into Mobile2 "+" values (1,'Nokia',6000,'Black')");

stmt.executeUpdate("insert into Mobile2 "+" values (2,'SamSung',6000,'White')");

stmt.executeUpdate("insert into Mobile2 "+" values (3,'Oppo',6000,'Gray')");

stmt.executeUpdate("insert into Mobile2 "+" values (4,'iphone',6000,'Black')");

System.out.println("Record inserted Succesfully");

ResultSetrs=stmt.executeQuery("select * from Mobile2");

System.out.println("Model_No\t"+"Company_Name\t"+"Price\t"+"Color");

 

while(rs.next( ))

{

System.out.println("\n"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getInt(3)+"\t"+rs.getString(4));

}

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output:-

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip13_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip13_1

Connection Established

Table Created Successfully

Record inserted Succesfully

Model_NoCompany_Name    Price   Color

 

1       Nokia   6000    Black

 

2       SamSung 6000    White

 

3       Oppo    6000    Gray

 

4       iphone  6000    Black

 

Slip 14 :-

Q2. Write a JDBC program in java to display details of Book_Sales(SalesID, Date, Amount)  of selected month in JTable. Book_sales table is already created.  (Use JCombo component for Month selection)       

 

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import java.sql.*;

import javax.swing.*;

public class slip14_2 extends JFrame implements ItemListener

{

 JComboBox cb;

 String head[ ]={"SalesId","Date","Amount"};

 String as[ ][ ]=new String[10][10];

public static void main(String args[ ])

{

new slip14_2( ).show( );

}

public slip14_2( )

{

cb=new JComboBox( );

cb.addItem("Jan");

cb.addItem("Feb");

cb.addItem("March");

cb.addItem("April");

cb.addItem("May");

cb.addItem("June");

cb.addItem("July");

cb.addItem("Aug");

cb.addItem("Sept");

cb.addItem("Oct");

cb.addItem("Nov");

cb.addItem("Dec");

cb.setBounds(350,20,100,20);

add(cb);

cb.addItemListener(this);

 

setLayout(null);

setSize(500,500);

setVisible(true);

}

public void itemStateChanged(ItemEvent ie)

{

String str=cb.getSelectedItem( ).toString( );

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=DriverManager.getConnection("jdbc:odbc:mydsn2");

Statement stmt=con.createStatement( );

ResultSet rs=stmt.executeQuery("select * from BookSales where Date like '"+str+"%'");

int i=0;

while(rs.next( ))

{

as[i][0]=rs.getString("SalesId");

as[i][1]=rs.getString("Date");

as[i][2]=rs.getString("Amount");

i++;

}

con.close( );

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTable jt=new JTable(as,head);

JScrollPane pane=new JScrollPane(jt);

add(pane);

pane.setBounds(0,0,300,400);

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output:-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip14_2.java

Note: slip14_2.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip14_2

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

                                                         Slip 15

Q1. Write a JDBC program in java to update an address of given customer(cid,cname,address) and display updated details.                                                                                  [15]

 

import java.io.*;

import java.sql.*;

class sl15_1

{

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

{

try

{

Connection con;

Statement stmt;

ResultSet rs;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

stmt=con.createStatement( );

System.out.println("Connection Established.....!!!!!!!!!!!!!!");

System.out.println("Enter cid:-");

int cid=Integer.parseInt(br.readLine( ));

System.out.println("Enter Address:-");

String add=br.readLine( );

stmt.executeUpdate("update customer set address='"+add+"' where cid="+cid+" ");

rs=stmt.executeQuery("select * from customer");

while(rs.next( ))

{

System.out.println("\n"+rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getInt(4));

}

rs.close( );

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

                            

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac sl15_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java sl15_1

Connection Established.....!!!!!!!!!!!!!!

Enter cid:-

1

Enter Address:-

perne

 

1 lmn perne 1236588966

 

 

 

 

 

 

 

 

 

 

                                                             Slip 17

Q1.  Write a java program which will display name and priority of current thread. Change name of Thread to MyThread and priority to 2. Display the details of Thread.                        

import java.io.*;

class slip17_1

{

public static void main(String a[])

{

String S;

int p;

Thread t=Thread.currentThread();

S=t.getName();

System.out.println("\n Current thread name:" +S);

p=t.getPriority();

System.out.println("\n Current thread priority:" +p);

t.setName("My Thread");

S=t.getName();

System.out.println("\n Changed Name:"+S);

t.setPriority(2);

p=t.getPriority();

System.out.println("\n Changed Priority:" +p);

}

}

Output:-

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip17_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip17_1

 

 Current thread name:main

 

 Current thread priority:5

 

 Changed Name:My Thread

 

 Changed Priority:2

 

 

 

 

 

 

 

Q2.  Write a JDBC application using swing for the following:

 

Type DDL Query

       

                                                                                                                       

 

 

 

Drop Table

Create Table

Alter Table

 

 

 

 


[25]

 

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.sql.*;

class slip17_2 extends JFrame implements ActionListener

{

JLabel l1;

JButton b1,b2,b3;

JTextArea t1,t2;

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

{

new slip17_2( ).show( );

}

slip17_2( )

{

l1=new JLabel("Type DDL Query:-");

t1=new JTextArea(30,30);

t2=new JTextArea(30,30);

b1=new JButton("Create Table");

b2=new JButton("Alter Table");

b3=new JButton("Drop Table");

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

setVisible(true);

setLayout(new GridLayout(2,3));

setSize(500,500);

add(l1);

add(t1);

add(t2);

add(b1);

add(b2);

add(b3);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent ae)

{

if(ae.getSource( )==b1)

{

try

{

Connection con;

 

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

String query=t1.getText( );

Statement stmt=con.createStatement( );

stmt.executeUpdate(query);

JOptionPane.showMessageDialog(null,"Table Created");

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

if(ae.getSource( )==b2)

{

try

{

Connection con;

 

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

String query=t1.getText( );

Statement stmt=con.createStatement( );

stmt.executeUpdate(query);

JOptionPane.showMessageDialog(null,"Table Altered");

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

 

if(ae.getSource( )==b3)

{

try

{

Connection con;

 

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

String query=t1.getText( );

Statement stmt=con.createStatement( );

stmt.executeUpdate(query);

JOptionPane.showMessageDialog(null,"Table Dropped");

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

 

}

 

}

 

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip17_2

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip17_2.java

Note: slip17_2.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Slip18:-

Q18_1. Write a java program using multithreading to execute the

threads sequentially.(Use Synchronized Method)                                                                              

 

import java.io.*;

class PrintDemo

{

public void printCount( )

{

try

{

for(int i=5;i>0;i--)

{

System.out.println("Counter --------" +i);

}

}

catch(Exception e)

{

System.out.println("Thread interrupted");

}

}

}

class ThreadDemo extends Thread

{

private Thread t;

private String threadName;

PrintDemo PD;

ThreadDemo(String name,PrintDemo pd)

{

threadName=name;

PD=pd;

}

public void run( )

{

synchronized(PD)

{

PD.printCount( );

}

System.out.println("Thread"+ threadName+"exiting");

}

public void start( )

{

System.out.println("Starting"+threadName);

if(t==null)

{

t=new Thread(this,threadName);

t.start( );

}

}

}

public class Slip18_1

{

public static void main(String a[ ])

{

PrintDemo PD=new PrintDemo( );

ThreadDemo T1=new ThreadDemo("Thread-1",PD);

ThreadDemo T2=new ThreadDemo("Thread-2",PD);

T1.start( );

T2.start( );

try

{

T1.join( );

T2.join( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output :-

C:\Program Files\Java\jdk1.6.0_20\bin>javac Slip18_1.java

C:\Program Files\Java\jdk1.6.0_20\bin>java Slip18_1

StartingThread-1

StartingThread-2

Counter --------5

Counter --------4

Counter --------3

Counter --------2

Counter --------1

ThreadThread-1exiting

Counter --------5

Counter --------4

Counter --------3

Counter --------2

Counter --------1

ThreadThread-2exiting

 

Slip 21

Q1. Write a JDBC Program in java to display the names of Employees starting with ‘S’ character.                                                                                                      [15]

 

Slip21_1.java

 

import java.sql.*;

public class slip21_1

{

public static void main(String args[ ])

{

Connection con;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

 

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

if(con==null)

{

System.out.println("Connection Failed");

System.exit(1);

}

System.out.println("Connection Established");

Statement stmt=con.createStatement( );

ResultSet rs=stmt.executeQuery("select * From employee where ename like 'S%' ");

System.out.println("eno\t"+"ename\t"+"department\t"+"sal\t");

while(rs.next( ))

{

System.out.println("\n"+rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));

}

con.close( );

rs.close( );

stmt.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip21_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip21_1

Connection Established

eno     ename   department      sal

 

3            Suraj      biology               25

 

4            suman     history              12

 

java.sql.SQLException: ResultSet is closed

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Slip22:-

Q2. Write a java program to create a student table with field’s rno, name and per. Insert values in the table. Display all the details of the student on screen. (Use PreparedStatement Interface)

                                                                                                                    [25]

 

import java.io.*;

import java.sql.*;

class slip22_2

{

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

{

try

{

Connection con;

Statement stmt;

ResultSet rs;

PreparedStatement ps;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

System.out.println("Connection Established......!!!!!!!!!!!");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

stmt=con.createStatement( );

stmt.executeUpdate("create table student(rno number,name varchar(20),per varchar(10))");

 

ps=con.prepareStatement("insert into student values(?,?,?)");

System.out.println("Enter rno:-");

int rno=Integer.parseInt(br.readLine( ));

ps.setInt(1,rno);

System.out.println("Enter name:-");

String name=br.readLine( );

ps.setString(2,name);

System.out.println("Enter per:-");

String per=br.readLine( );

ps.setString(3,per);

ps.executeUpdate( );

rs=stmt.executeQuery("select * from student");

System.out.println("Rno\t"+"Name\t"+"Percentage\t");

while(rs.next( ))

{

System.out.println("\n"+rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

}

rs.close( );

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip22_2.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip22_2

Connection Established......!!!!!!!!!!!

Enter rno:-

1

Enter name:-

Miss.Nikita

Enter per:-

87%

Rno     Name    Percentage

 

1     Miss.Nikita      87%

 

 

 

 

 

 

 

 

Slip24:-

Q2. Write a java program to accept the details of college (CID, CName, Address, year) and store it into database (Use Swing and PreparedStatement interface)                                         [25]

 

import java.io.*;

import java.sql.*;

class slip24_2

{

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

{

try

{

Connection con;

Statement stmt;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

System.out.println("connection Established.......!!!!!!!");

stmt=con.createStatement( );

PreparedStatement ps=con.prepareStatement("insert into College values(?,?,?,?)");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter Cid:-");

int C_Id=Integer.parseInt(br.readLine( ));

ps.setInt(1,C_Id);

System.out.println("Enter CName:-");

String C_Name=br.readLine( );

ps.setString(2,C_Name);

System.out.println("Enter Year:-");

int Year=Integer.parseInt(br.readLine( ));

ps.setInt(3,Year);

System.out.println("Enter C Address:-");

String Address=br.readLine( );

ps.setString(4,Address);

 

int k=ps.executeUpdate( );

if(k>0)

{

System.out.println("record inserted Successfully");

}

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

Output :-

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip24_2.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip24_2

connection Established.......!!!!!!!

Enter Cid:-

2

Enter CName:-

MIT

Enter Year:-

1999

Enter C Address:-

Pune

record inserted Successfully

 

 

 

 

 

 

 

 

 

 

 

                                                 Slip 26 :-

Q1. Write a Multithreading program in java to display all the alphabets from A to Z after 3 seconds.                                                                                                

import java.io.*;

 import java.util.*;

class mythread implements Runnable{

Thread t;

public mythread(){

t=new Thread(this);

t.start();}

public void run()

{

char ch;

for(ch='a';ch<='z';ch++)

{

System.out.println(ch);

try{

Thread.sleep(3000);}

catch(Exception e){}}}}

class demo

{public static void main(String s[]){

mythread m=new mythread();}}

 

output:-

C:\Program Files\Java\jdk1.6.0_20\bin>javac demo.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java demo

a

b

c

d

e

f

g

h

i

j

k

l

m

n

o

p

q

r

s

t

u

v

w

x

y

z

 

                                                                 Slip 27

Q1. Write a JDBC program to delete the details of given employee (ENo EName Salary). Accept employee ID through command line.                                                                                                                                                                                              [15]

import java.io.*;

import java.sql.*;

class slip27_1

{

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

{

Connection con;

Statement stmt;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

 

 

con=DriverManager.getConnection("jdbc:odbc:mydsn2");

System.out.println("Connection EStablished");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter Employee number to delete");

int e_no=Integer.parseInt(br.readLine( ));

stmt=con.createStatement( );

int no=stmt.executeUpdate("delete * from employee where eno="+e_no);

if(no>0)

{

System.out.println("Record deleted successfully");

}

stmt.close( );

con.close( );

}

catch(Exception e)

{

System.out.println(e);

}

}

}

 

Output :-

 

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac slip27_1.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java slip27_1

Connection EStablished

Enter Employee number to delete

2

Record deleted successfully

 

 

 

 

 

 

 

SLIP 7:  Write a JSP program to calculate sum of first and last digit of a given number. Display sum in Red Color with font size 18.

 

HTML FILE

 

<!DOCTYPE html>

<html>

<body>

<form method=post action="Slip7.jsp">

Enter Any Number : <Input type=text name=num><br><br>

<input type=submit value=Display>

</form>

</body>

</html>

 

JSP FILE:

 

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<body>

<%! int n,rem,r; %>

<% n=Integer.parseInt(request.getParameter("num"));

      if(n<10)

     {     

       out.println("Sum of first and last digit is   ");

%><font size=18 color=red><%= n %></font>

<%

     }

    else

    {

      rem=n%10;

      do{

                 r=n%10;

                 n=n/10;

            }while(n>0);

         n=rem+r;

 

 

 

 

        out.println("Sum of first and last digit is    ");

%><font size=18 color=red><%= n %></font>

<%

     }

%>

</body>

</html>

OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SLIP16:  Write a JSP page, which accepts user name in a text box and greets the user according to the time on server machine.

 

SLIP16_FIRST..jsp:

 

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

    <body>

        <form action="Slip16.jsp" method="post">

            Enter Your Name : <input type="text" name="name"><br>

           

            <input type="submit" value="Submit">

        </form>

    </body>

</html>

 

 

SLIP16.jsp:

 

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

 

<%

 

    String name = request.getParameter("name");

   

   Calendar rightnow = Calendar.getInstance();

   int time = rightnow.get(Calendar.HOUR_OF_DAY);

  

    if(time > 0 && time <= 12)

    {

        out.println("Good Morning"+name);

    }

      else if(time < 12 && time >=16)

      {

          out.println("Good Afternoon"+name);

      }

      else

      {

          out.println("Good Night"+name);

      }

%>

 

 

OUT PUT:

 

 

 

 

 

 

 

 

SLIP19: Create a JSP page to accept a number from an user and display it in words: Example: 123  One Two Three. The output should be in red color.

 

HTML FILE :

 

<!DOCTYPE html>

<html>

<body>

<form method=get action="Slip19.jsp">

Enter Any Number : <input type=text name=num><br><br>

<input type=submit value="Display">

</form>

</body>

</html>

 

JSP FILE:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<body>

<font color=red>

<%! int i,n;

String s1;

%>

<%   s1=request.getParameter("num");

n=s1.length();

i=0;

do

{

            char ch=s1.charAt(i);

            switch(ch)

            {

                        case '0': out.println("Zero  ");break;

                        case '1': out.println("One  ");break;

                        case '2': out.println("Two  ");break;

                        case '3': out.println("Three  ");break;

                        case '4': out.println("Four ");break;

                        case '5': out.println("Five  ");break;

                        case '6': out.println("Six  ");break;

                        case '7': out.println("Seven  ");break;

                        case '8': out.println("Eight  ");break;

 

 

 

                        case '9': out.println("Nine  ");break;

            }

            i++;

}while(i<n);

%>

</font>

</body>

</html>

 

OUTPUT:

 

 

 

 

 

 

 

 

 

 

SLIP 20:  Write a JSP program to display the details of Hospital (HNo, HName, Address) in tabular form on browser

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

 

<html><body>

<%@ page import="java.sql.*;" %>

<%! int hno;

String hname,address;  %>

<%

 

try{

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            Connection cn=DriverManager.getConnection("jdbc:odbc:hospital_data","","");

 

            Statement st=cn.createStatement();

            ResultSet rs=st.executeQuery("select * from Hospital");

            %>

                        <table border="1" width="40%">

                        <tr>

                        <td>Hospital No</td>

                        <td>Name</td>

                        <td>Address</td>

                        </tr>

                        <%      while(rs.next())

                        {

                                    %>

                                                <tr> <td><%= rs.getInt("hno") %></td>

                                                <td><%= rs.getString("hname") %></td>

                                                <td><%= rs.getString("address") %></td>

                                                </tr>

                                                <%

                        }

            cn.close();

}catch(Exception e)

{      

            out.println(e); 

 

 

 

 

   

}

%>

</body></html>

 

 

OUTPUT:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SLIP23 : Write a JSP script to accept the details of Student (RNo, SName, Gender, Comp_Know ,Class) and display it on the browser. Use appropriate controls for accepting data.

 

HTML FILE:

<!DOCTYPE html>

<html>

<head>

<title></title>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>

<body>

<h1>Enter Information</h1>

<form action="Slip23.jsp" method="post">

Roll No : <input type="text" name="rno"><br><br>

 

Name : <input type="text" name="name"><br><br>

 

Gender : <input type="radio" name="gender" value="Male" checked>Male

<input type="radio" name="gender" value="Female">Female

<br><br>

 

Comp_Know : <input type="radio" name="know" value="Yes" checked>Yes

<input type="radio" name="know" value="No">No

<br><br>

 

Class :

<select name="Class">

<option value="11">11Th</option>

<option value="12">12Th</option>

<option value="FY">FY</option>

<option value="SY">SY</option>

<option value="TY">TY</option>

</select>

<br><br>

 

 

 

 

 

 

 

<input type="submit" value="Submit">

</form>

</body>

</html>

 

 

 

 

JSP FILE :

 

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<%

 

    int rno = Integer.parseInt(request.getParameter("rno"));

   

    String s_name = request.getParameter("name");

   

    String s_gender = request.getParameter("gender");

   

    String s_know = request.getParameter("know");

   

    String s_class = request.getParameter("Class");

         

    out.println("\nRoll No :"+rno);

    out.println("\nName :"+s_name);

    out.println("\nGender :"+s_gender);

    out.println("\nComp_Know :"+s_know);

    out.println("\nClass :"+s_class);

    %>

 

 

 

 

 

 

 

 

 

OUTPUT:

 

 

 

 

 

 

 

 

Slip 4 : Write a JSP program to create a shopping mall. User must be allowed to do

purchase from two pages. Each page should have a page total. The third page should

display a bill, which consists of a page total of whatever the purchase has been done and

print the total

Slip4_first.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<form action="Slip4_Second.jsp" method="post">

<h1>Shopping Mall</h1>

Rice :

<select name="rice">

<option value="2">2 Kg</option>

<option value="5">5 Kg</option>

<option value="10">10 Kg</option>

<option value="15">15 Kg</option>

</select>

Wheat :

<select name="wheat">

<option value="2">2 Kg</option>

<option value="5">5 Kg</option>

<option value="10">10 Kg</option>

<option value="15">15 Kg</option>

</select>

<input type="submit" value="Submit">

</form>

</body>

</html>

Slip4_Second.jsp

 

 

 

 

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<%

String rice = request.getParameter("rice");

int r = Integer.parseInt(rice);

String wheat = request.getParameter("wheat");

int w = Integer.parseInt(wheat);

int tr = r * 40;

int wt = w * 60;

int pt = tr + wt;

session.setAttribute("first_Total", pt);

%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1>Shopping Mall</h1>

<form action="Slip4_Third.jsp" method="post">

Maggi :

<select name="maggi">

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

</select>

Good Day :

<select name="good">

<option value="1">1</option>

<option value="2">2</option>

<option value="3">3</option>

<option value="4">4</option>

<option value="5">5</option>

</select>

<input type="submit" value="Submit">

</form>

</body>

</html>

Slip4_Third.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>

<%

String m = request.getParameter("maggi");

String g = request.getParameter("good");

 

 

 

 

int mp = Integer.parseInt(m);

int gp = Integer.parseInt(g);

int mpt = mp * 10;

int gpt = gp * 10;

int secont_total = mpt + gpt;

int first_Total = (Integer)request.getSession().getAttribute("first_Total");

int grand_Total = first_Total + secont_total;

%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>JSP Page</title>

</head>

<body>

<h1>Shopping Mall</h1>

<h1>First Page Total <%=first_Total%></h1><br>

<h1>Second Page Total <%=secont_total%></h1><br>

<h1>Total Bill<%=grand_Total%></h1><br>

</body>

</html>

 

 

 

 

SERVLET PROGRAMS

https://malisir.blogspot.in/p/title-write-multithreading-program-in.html

 

 

 

 

Title :- Write a SERVLET application to accept username and password, search them into database, if found then display appropriate message on the browser otherwise display error message.

UserPass.html

<html>

<body>

<form method=post action="http://localhost:4141/Program/servlet/UserPass">

User Name :<input type=text name=user><br><br>

Password :<input type=text name=pass><br><br>

<input type=submit value="Login">

</form>

</body>

</html>

 

UserPass.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public class UserPass extends HttpServlet

{

    public void doGet(HttpServletRequest request, HttpServletResponse response)

        throws IOException, ServletException

    {

            PrintWriter out = response.getWriter();

            try{

                        String us=request.getParameter("user");

                        String pa=request.getParameter("pass");

                         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

 

 

 

 

 

                        Connection cn=DriverManager.getConnection("jdbc:odbc:dsn2","","");

                        Statement st=cn.createStatement();

                        ResultSet rs=st.executeQuery("select * from UserPass");

                        while(rs.next())

                      {

                        if(us.equals(rs.getString("user"))&&pa.equals(rs.getString("pass")))

                        out.println("Valid user");

                        else

                        out.println("Invalid user");

                      }

                }catch(Exception e)

                  {     

                      out.println(e);           

                  }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)

    throws IOException, ServletException

    {

        doGet(request, response);

    }

}

 

Web.xml file(servlet entry)

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app>

<servlet>

        <servlet-name>UserPass</servlet-name>

        <servlet-class>UserPass</servlet-class>

    </servlet>

    <servlet-mapping>

        <servlet-name>UserPass</servlet-name>

        <url-pattern>/servlet/UserPass</url-pattern>

    </servlet-mapping>

</web-app>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Title :- Write a SERVLET program which counts how many times a user has visited a web page. If user is visiting the page for the first time, display a welcome message. If the user is revisiting the page, display the number of times visited. (Use Cookie)

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class VisitServlet extends HttpServlet

{

    static int i=1;

    public void doGet(HttpServletRequest request, HttpServletResponse response)

        throws IOException, ServletException

    {

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        String k=String.valueOf(i);

        Cookie c = new Cookie("visit",k);

        response.addCookie(c);

        int j=Integer.parseInt(c.getValue());

        if(j==1)

        {

            out.println("Welcome");

        }

        else

        {

            out.println("You visited "+i+" times");

        }

                i++;                       

    }

}

 

 

Web.xml file(servlet entry)

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app>

<servlet>

        <servlet-name>VisitServlet</servlet-name>

 

 

 

 

 

 

 

        <servlet-class>VisitServlet</servlet-class>

    </servlet>

<servlet-mapping>

        <servlet-name>VisitServlet</servlet-name>

        <url-pattern>/servlet/VisitServlet</url-pattern>

    </servlet-mapping>

</web-app>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Slip14  Q1.

 Write a Socket program in java which displays the server machine’s date and time on the client machine.                  

import java.net.*;

import java.io.*;

import java.util.Date;

 

public class Server_Slip14_1

{

            public static void main(String g[])throws

UnknownHostException, IOException

            {

                        ServerSocket ss=new ServerSocket(4444);

                        System.out.println("server started");

                        Socket s=ss.accept();

                        System.out.println("Client connected");

                        Date d=new Date();

                        int m=d.getMonth();

                        m=m+1;

                        int y=d.getYear();

                        y=y+1900;

                String time=""+d.getHours()+":"+d.getMinutes()+

":"+d.getSeconds()+" Date is "+d.getDate()+"/"+m+"/"+y;

                        OutputStream os=s.getOutputStream();

                        DataOutputStream dos=new DataOutputStream(os);

                        dos.writeUTF(time);

            }

}

Client Program:

 import java.net.*;

import java.io.*;

import java.util.*;

public class Client_Slip14_1

{

       public static void main(String args[]) throws Exception

       {

              Socket s = new Socket("localhost",4444);

              DataInputStream dos = new DataInputStream(s.

getInputStream());

                        String time = dos.readUTF();

                 System.out.println("Current date and time is "+time);

  }

}

Output:

C:\Program Files\Java\jdk1.6.0_20\bin>javac Server_Slip14_1.java

C:\Program Files\Java\jdk1.6.0_20\bin>java Server_Slip14_1

server started

Client connected

C:\Program Files\Java\jdk1.6.0_20\bin>javac Client_Slip14_1.java

C:\Program Files\Java\jdk1.6.0_20\bin>java Client_Slip14_1

Current date and time is 23:40:58 Date is 6/2/2018

Slip6 Q2.

Write a SOCKET program in java to check whether given file is present on server or not, If it is present then display its content on the server’s machine otherwise display error message.

Slip 6

import java.io.*;

import java.net.*;

class S_Slip6_2

{

public static void main(String a[]) throws Exception

{

ServerSocket ss = new ServerSocket(1000);

System.out.println("Server is waiting for client : ");

Socket s =ss.accept();

System.out.println("Client is connected");

DataInputStream dis=new DataInputStream(s.getInputStream());

DataOutputStream dos=new DataOutputStream(s.getOutputStream());

String fname =(String)dis.readUTF();

File f = new File(fname);

if(f.exists())

{

System.out.println("file is exists");

FileInputStream fin = new FileInputStream(fname);

int ch;

String msg = "";

while((ch=fin.read())!=-1)

{

msg=msg+(char)ch;

}

dos.writeUTF(msg);

}

else

dos.writeUTF("0");

}

}

Client Program:

import java.io.*;

import java.net.*;

class C_Slip6_2

{

public static void main(String a[]) throws Exception

{

Socket s = new Socket("localhost",1000);

System.out.println("client is connected : ");

DataInputStream dis=new DataInputStream(s.getInputStream());

DataOutputStream dos=new DataOutputStream(s.getOutputStream());

BufferedReader br = new BufferedReader(new

InputStreamReader(System.in));

System.out.println("Enter file name : ");

String fname = br.readLine();

dos.writeUTF(fname);

String msg = (String)dis.readUTF();

if(msg.equals("0"))

System.out.println("File not present ");

else

{

System.out.println("Content of the file is : \n");

System.out.println(msg);

}

}

}

Output: C:\Program Files\Java\jdk1.6.0_20\bin>javac S_Slip6_2.java

C:\Program Files\Java\jdk1.6.0_20\bin>java S_Slip6_2

Server is waiting for client

C:\Program Files\Java\jdk1.6.0_20\bin>javac C_Slip6_2.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java C_Slip6_2

client is connected :

Enter file name :

abc.txt

Content of the file is :

 Welcome to BJS Arts science and commerce college

 

 

 

 

 

Slip 13 Q2. 

Write a Socket program in java for simple stand alone chatting application.                        [25]

 

import java.io.*;

import java.net.*;

class C_Slip13_2

{

public static void main(String a[]) throws Exception {

Socket s = new Socket("localhost",1000);

System.out.println("client is connected : ");

DataInputStream ios=new DataInputStream(s.getInputStream());

DataOutputStream dos=new DataOutputStream(s.getOutputStream());

BufferedReader br = new BufferedReader(new

InputStreamReader(System.in));

String s1,s2;

while(true)

{

System.out.println("Server ....");

s1=br.readLine();

dos.writeUTF(s1);

 

s2=(String)ios.readUTF();

 

if(s2.equals("end") || s2.equals("END"))

 

{

System.out.println("chatting terminated");

break;

 

}

System.out.println("Client "+s2);

}

}

}

 

import java.io.*;

import java.net.*;

 

class S_Slip13_2

{

 

public static void main(String a[]) throws Exception {

ServerSocket ss = new ServerSocket(1000);

 

System.out.println("Server is waiting for client : ");

Socket s =ss.accept();

System.out.println("Client is connected");

 

DataInputStream ios=new DataInputStream(s.getInputStream()); DataOutputStream dos=new DataOutputStream(s.getOutputStream());

 

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String s1,s2;

while(true)

 

{

s1 = (String)ios.readUTF();

if(s1.equals("end") || s1.equals("END"))

{

System.out.println("chatting terminated");

 

break;

}

System.out.println("Client "+s1);

System.out.println("Server ...");

s2 = br.readLine();

dos.writeUTF(s2);

if(s2.equals("end") || s2.equals("END"))

 

{

System.out.println("chatting terminated");

break;

}

}

}

}

Output:

C:\Program Files\Java\jdk1.6.0_20\bin>javac C_Slip13_2.java

C:\Program Files\Java\jdk1.6.0_20\bin>java C_Slip13_2

client is connected :

Server ....

hi

Client hi

Server ....

how are u

Client i am fine

Server ....

whats going on

Client nothing

Server ....

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac S_Slip13_2.java

 

C:\Program Files\Java\jdk1.6.0_20\bin>java S_Slip13_2

Server is waiting for client :

Client is connected

Client hi

Server ...

hi

Client how are u

Server ...

i am fine

Client whats going on

Server ...

Nothing

 

Slip20 Q2):

Chatting Application using AWT

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import java.util.*;

class Awtcchat extends Frame implements ActionListener {

TextField t1;

 

Button b1;

Socket s;

Scanner sc;

 

DataOutputStream dos;

DataInputStream dis;

String msg;

Label l1,l2;

Awtcchat() throws Exception

 

{

 

setVisible(true);

setSize(600,600);

t1=new TextField(50);

b1=new Button("send");

l1=new Label("Sever");

l2=new Label();

 

setLayout(new FlowLayout());

add(l1);

add(l2);

add(t1);

add(b1);

 

b1.addActionListener(this);

 

s=new Socket("localhost",5000);

 

sc=new Scanner(System.in);

 

dos=new DataOutputStream(s.getOutputStream()); dis=new DataInputStream(s.getInputStream());

 

 

}

 

public void actionPerformed(ActionEvent ae)

 

{

if(ae.getSource()==b1)

{

try

{

 

msg=t1.getText();

dos.writeUTF(msg);

t1.setText("");

 

String reply=(String)dis.readUTF();

l2.setText(reply);

}

 

catch(Exception e){}

}

}

public static void main(String a[]) throws Exception {

Awtcchat ob=new Awtcchat();

}

}

Server Program:

 

import java.awt.*;

 

import java.awt.event.*;

import java.io.*;

import java.net.*;

import java.util.*;

 

class Awtschat extends Frame implements ActionListener {

 

TextField t1;

Button b1;

ServerSocket ss;

Socket s;

Scanner sc;

 

DataOutputStream dos;

DataInputStream dis;

String msg;

Label l1,l2;

Awtschat() throws Exception

 

{

 

setVisible(true);

setSize(600,600);

t1=new TextField(50);

b1=new Button("send");

l1=new Label("Client");

l2=new Label();

setLayout(new FlowLayout());

 

add(l1);

add(l2);

add(t1);

add(b1);

b1.addActionListener(this);

 

ss=new ServerSocket(5000);

 

sc=new Scanner(System.in);

s=ss.accept();

 

dos=new DataOutputStream(s.getOutputStream()); dis=new DataInputStream(s.getInputStream());

 

 

}

 

public void actionPerformed(ActionEvent ae)

{

if(ae.getSource()==b1)

 

{

 

try

 

{

 

String reply=(String)dis.readUTF();

 

l2.setText(reply);

 

msg=t1.getText();

dos.writeUTF(msg);

t1.setText("");

}catch(Exception e){}

}}

public static void main(String a[]) throws Exception {

Awtschat ob=new Awtschat();

}

}

Output:

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac Awtschat.java

C:\Program Files\Java\jdk1.6.0_20\bin>java Awtschat

 

C:\Program Files\Java\jdk1.6.0_20\bin>javac Awtcchat.java

C:\Program Files\Java\jdk1.6.0_20\bin>java Awtcchat

 

 

 

 

 

 

 

 

 

 

 

Post a Comment

0 Comments