Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Java Programming Lab

PART-A
1. Write a Java program to demonstrate method overloading.

class overloadDemo
{
int volume(int s)
{
return(s*s*s);
}
float volume (float r, int h)
{
return(3.14f*r*r*h);
}
long volume(long l,int b,int h)
{
return (l*b*h);
}
}
class overload
{
public static void main(String args[])
{
overloadDemo ob=new overloadDemo();
System.out.println("volume of cube: " + ob.volume(10));
System.out.println("volume of cylinder: "+ ob.volume(2.5f,8));
System.out.println("volume of rectangular box: " + ob.volume(100l,75,15));
}}
output:
volume of cube: 1000
volume of cylinder: 157.0
volume of rectangular box: 11250

1
2. Write a Java program to sort a list of numbers.

class Numbersorting
{
public static void main(String args[])
{
int number[]={55,40,80,65,71};
int n=number.length;
System.out.println("Given list:");
for(int i=0;i<n;i++)
System.out.print(" "+ number[i]);
System.out.print("\n");
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
System.out.println("Sorted list:");
for(int i=0;i<n;i++)
System.out.print(" " + number[i]);
System.out.println(" ");
}
}

output:
Given list:
55 40 80 65 71
Sorted list:
80 71 65 55 4

2
3. Write a Java program to demonstrate manipulation of strings.

class stringManipulation
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Object language");
System.out.println("Original string: " + str);
//obtaining string length
System.out.println("Length of string: " + str.length());
//Accessing characters in a string
for(int i=0;i<str.length();i++)
{
int p=i+1;
System.out.println("Character at position: " + p + " is " + str.charAt(i));
}
//Inserting a string in the middle
String astring = new String (str.toString());
int pos= astring.indexOf(" language");
str.insert(pos," Orient ");
System.out.println("Modified string:" + str);
//Modifying characters
str.setCharAt(6,'_');
System.out.println("String now:" + str);
//Appending a string at the end
str.append(" improves security. ");
System.out.println("Appended string :" + str);
}
}

3
4. Write a Java program to demonstrate single inheritance.

class room
{
int length,breadth;
room(int x,int y)
{
length=x;
breadth=y;
}

int area()
{
return(length*breadth);
}
}

class newroom extends room


{
int height;
newroom(int x,int y,int z)
{
super(x,y);
height=z;
}

int volume()
{
return(length*breadth*height);
}
}

class singleinheritance
{
public static void main(String args[])
{
newroom room1=new newroom(14,12,10);
int area1=room1.area();
int volume1=room1.volume();
System.out.println("area1= " + area1);
System.out.println("volume1= " + volume1);
}
}

4
5. Write a Java program to sort the names using vectors.

import java.util.*;
class vectorsort
{
public static void main(String args[])
{
Vector list=new Vector();
List.add(“adcdfd”);

int length=args.length;
for(int i=0;i<length;i++)
list.addElement(args[i]);
int size=list.size();
String listArray[]=new String[size];
list.copyInto(listArray);
String temp=null;
for(int i=0;i<size;i++)
for(int j=i+1;j<size;j++)
if(listArray[j].compareTo(listArray[i])<0)
{
temp=listArray[i];
listArray[i]=listArray[j];
listArray[j]=temp;
}
System.out.println("sorted list is ");
for (int i=0;i<list.size();i++)
System.out.println(listArray[i]);
}
}

5
6. Write a Java program to demonstrate Arrayindexoutofbounds and arithmetic Exceptions.

class TryCatch
{
public static void main(String args[])
{
int array[]={0,0};
int num1,num2,result=0;
num1=100;
num2=0;
System.out.println("Exceptions caught are:-");

try
{
result=num1/num2;
}
catch(ArithmeticException e)
{
System.out.println("Error..... Division by zero");
}

try
{
System.out.println(num1/array[2]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Error..........ArrayIndexOutOfBounds");
}
}
}

6
7. Write a Java program to demonstrate Multiple Threading.

class ThreadDemo implements Runnable


{
Thread t;
ThreadDemo()
{
t=new Thread(this);
System.out.println("ChildThread:" );
t.start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println("ChildThread:" + i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("ChildThread Interrupted ");
}
System.out.println("Exiting ChildThread");
}
}
class MultipleThread
{
public static void main(String arg[])
{

7
new ThreadDemo();
try
{
for(int i=5;i>0;i--)
{
System.out.println("MainThread:" + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("MainThread Interrupted");
}
System.out.println("Exiting MainThread ");
}

8
8. Write an applet to display the sum of two digits.
/* <applet code="UserIn.class" width=600 height=200 > </applet> */
import java.awt.*;
import java.applet.*;
public class UserIn extends Applet
{
TextField text1,text2;
public void init()
{
text1=new TextField(8);
text2=new TextField(8);
add(text1);
add(text2);
text1.setText("0");
text2.setText("0");
}
public void paint(Graphics g)
{
int x=0,y=0,z=0;
String s1,s2,s;
g.drawString("Input a number in each box" ,10, 50);
try
{
s1=text1.getText();
x=Integer.parseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2);
}
catch(Exception ex)
{}
z=x+y;

9
s=String.valueOf(z);
g.drawString("The sum is : " ,10,75);
g.drawString(s,100,75);
}
public boolean action(Event event, Object object)
{
repaint();
return true;
}
}

9. Write a Java program to display the IP address of your working machine.

import java.net.*;
class Inteladd
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress address=InetAddress.getLocalHost();
System.out.println(address);
}
}

10
10. Write a Java program to demonstrate free hand writing.

/*<applet code="SimpleKey.class" width=200 height=300 ></applet>*/

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class SimpleKey extends Applet implements KeyListener
{
String msg=" ";
int x=10,y=20;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
showStatus("key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("key up");
}
public void keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, x, y);
}
}

11
PART-B

1. Write a Java program to draw line, rectangle, circle ,oval and polygon with the help of
java graphic class.

//<applet code="Rect.class" width=200 height=200></applet>

import java.awt.*;
import java.applet.*;
public class Rect extends Applet
{
public void paint(Graphics g)
{
g.drawLine(700,20,800,760);
g.drawRect(30,60,40,50);
g.setColor(Color.green);
g.drawOval(80,180,200,120);
g.setColor(Color.red);
g.fillOval(270,30,100,100);
int x[]={500,420,220,500};
int y[]={500,620,20,500};
int n=4;
g.drawPolygon(x,y,n);
}
}

12
2. Write a Java applet to demonstrate Animation using threads.

/*<applet code="simpleimage.class" width=2222 height=1111>


<param name="img2" value="Sunset.jpg">
<param name="img1" value="Water lilies.jpg"></applet>*/
import java.awt.*;
import java.applet.*;
public class simpleimage extends Applet implements Runnable
{

Image img2;
Image img1;
Thread t;
public void init()
{
img2=getImage(getDocumentBase(), getParameter("img2"));
img1=getImage(getDocumentBase(),getParameter("img1"));
Thread t=new Thread(this);
t.start();
}
public void paint(Graphics g)
{
try
{
t.sleep(1000);
}
catch(InterruptedException e)
{
showStatus("thread Interrupted");
}
g.drawImage(img1,10,70,this);
try
{
t.sleep(10000);
}
catch(InterruptedException e)
{
showStatus("thread Interrupted");
}
g.drawImage(img2,210,110,this);
}
public void run()
{
for(; ;)
repaint();
}

13
}

3 . Write a Java program to demonstrate Access Control using packages.

// To demonstrate access control using Packages.

package package1;
public class ClassA
{
public void displayA()
{
System.out.println("ClassA");
}
}

//Note: Store the file ClassA.java in the folder package1 and compile it.

import package1.*;
class packageTest1
{
public static void main(String args[])
{
ClassA objectA=new ClassA();
objectA.displayA();
}
}

Output:

ClassA

14
package package2;
public class ClassB
{
protected int m=10;
public void displayB()
{
System.out.println("ClassB");
System.out.println("m=" + m);
}
}

//Store the file ClassB.java in the folder package2 and compile it.

import package1.ClassA;
import package2.*;
class packageTest2
{
public static void main(String args[])
{
ClassA objectA=new ClassA();
ClassB objectB=new ClassB();
objectA.displayA();
objectB.displayB();
}
}

Output:

ClassA
ClassB
m=10

15
4. Write a Java program to display the result of a student using multiple inheritance.

/student result using multiple inheritance.


class student
{
int rollNumber;
void getNumber(int n)
{
rollNumber=n;
}
void putNumber()
{
System.out.println("Roll No: " + rollNumber);
}
}
class Test extends student
{
float part1,part2;
void getMarks(float m1,float m2)
{
part1=m1;
part2=m2;
}
void putMarks()
{
System.out.println("Marks obtained");
System.out.println("part1=" + part1);
System.out.println("part2=" + part2);
}
}
interface sports
{
float sportwt=6.0f;
void putwt();
}
class Results extends Test implements sports
{
float total;
public void putwt()
{
System.out.println(" Sports wt= " + sportwt);
}
void display()
{
total=part1+part2+sportwt;
putNumber();

16
putMarks();
putwt();
System.out.println("Total score=" + total);
}
}
class Hybrid
{
public static void main(String args[])
{
Results stud=new Results();
stud.getNumber(1234);
stud.getMarks(27.5f,33.0f);
stud.display();
}
}

output:
Roll No: 1234
Marks obtained
part1= 27.5
part2= 33.0
sports wt =6.0
Total score = 66.5

17
5. Write a Java program to demonstrate simple calculator with the help of text fields, buttons.

// Applet to demonstrate Simple Calculator


/*<Applet code="simpleCalculator1.class" width=400 height=200></Applet>*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class simpleCalculator1 extends Applet
{
TextField text1,text2,text3;
public void init()
{
text1=new TextField(8);
text2=new TextField(8);
text3=new TextField(4);
add(text1);
add(text2);
add(text3);
text1.setText("0");
text2.setText("0");
text3.setText("0");
}
public void paint(Graphics g)
{
int x=0,y=0,z=0,i=0;
String s,s1,s2,s3;
g.drawString("Input a no in first and second box",10,50);
g.drawString("Input your choice in box three:",20,80);
g.drawString("1.Addition 2.Subtraction",20,100);
g.drawString("3.Multiplication 4.Division",20,30);
try
{
s1=text1.getText();
x=Integer.parseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2);
s3=text3.getText();
i=Integer.parseInt(s3);
}
catch(Exception e)
{
}
switch(i)
{
case 1:z=x+y;
break;

18
case 2:z=x-y;
break;
case 3:z=x*y;
break;
case 4:z=x/y;
break;
default:g.drawString("Invalid Input",40,50);
}
s=String.valueOf(z);
g.drawString("The result is",10,205);
g.drawString(s,100,205);
}
public boolean action(Event event,Object object)
{
repaint();
return true;
}
}

19
6. Write a Java program using I-O streams to count the number of words in a file.

import java.io.*;
class WordCount
{
public static int words=0;
public static void wc(InputStreamReader isr) throws IOException
{
int c=0;
boolean lastwhite=true;
String whitespace=" \n\t\r";
while((c=isr.read())!=-1)
{

int index=whitespace.indexOf(c);

if(index==-1)
{

if(lastwhite==true)
{
++words;
}
lastwhite=false;
}
else
{
lastwhite=true;
}
}
}
public static void main(String args[])
{
try
{
wc(new InputStreamReader(System.in));
}
catch(IOException ee)
{
return;
}
System.out.println("no of words="+words);

}
}

20
7. Write a Java program to copy characters from one file into another.

import java.io.*;
class CopyCharacters
{
public static void main(String args[])
{
File infile = new File("input.dat");
File outfile=new File("output.dat");
FileReader ins=null;
FileWriter outs=null;
try
{
ins=new FileReader(infile);
outs=new FileWriter(outfile);
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close();
outs.close();
}
catch(IOException ex)

{ }
}
}
}

21
8. Write a Java program to demonstrate Client Server Interaction.

1. Client

import java.io.*;
import java.net.*;
class Client
{
public static void main(String args[])
{
Try {
Socket ci=new Socket("127.0.0.1",5000);
DataInputStream din=new DataInputStream(ci.getInputStream());
DataOutputStream dout=new DataOutputStream(ci.getOutputStream());
int a=10,b=20,c;
String add="";
dout.writeInt(a);
dout.writeInt(b);
c=din.readInt();
add=String.valueOf(c);
System.out.println("addition of a,b is" +add);
dout.close();
}catch(Exception e) {}
}}

2. Server

import java.io.*;
import java.net.*;
class Server
{
public static void main(String args[])
{
try
{
ServerSocket s=new ServerSocket(5000);
Socket ci=s.accept();
DataInputStream din=new DataInputStream(ci.getInputStream());
DataOutputStream dout=new DataOutputStream(ci.getOutputStream());
int x=din.readInt();
int y=din.readInt();
int z=x+y;
dout.writeInt(z);
dout.close();
s.close();
}catch(Exception e){}

22
}}

9. Write a Java applet to calculate Area and Circumference of a circle using radio button and
checkbox.

// Java Applet to calculate Area & circumference of a circle


/*<applet code=area.class width=433 height=323></applet>*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class area extends Applet implements ItemListener
{
Checkbox cb1,cb2;
CheckboxGroup cbg;
TextField text1;
float area,radius,circum;
String r= " ";
String a=" ";
String c="";
public void init()
{
cbg=new CheckboxGroup();
cb1=new Checkbox("area");
cb2=new Checkbox("circum",cbg,false);
text1=new TextField(6);

add(text1);
add(cb1);
add(cb2);
text1.setText("0");
cb1.addItemListener(this);
cb2.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
try
{
r=text1.getText();
radius=Float.parseFloat(r);
if(e.getSource()==cb1)
{

area=3.14f*radius*radius;
a=String.valueOf(area);

}
else if(e.getSource()==cb2)
{
circum=3.14f*radius*2.0f;

23
c=String.valueOf(circum);
}}
catch(Exception ex){ }
repaint();
}
public void paint(Graphics g)
{
g.drawString("enter the radius in the textbox",30,20);
g.drawString("area:",10,40);
g.drawString("circumference:",10,80);
g.drawString(a,40,40);
g.drawString(c,150,80);
}}

11. Write a simple database and connect it using JDBC.

//create a simple database and connect it using JDBC


import java.sql.*;
public class DBconnect
{
public static void main(String args[])
{
ResultSet rs;
Connection con;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:LoginDetails");
Statement stmt=con.createStatement();
String selectQuery ="select * from login where userName='anil' ";
rs= stmt.executeQuery(selectQuery );
while(rs.next())
{
int uId=rs.getInt("userId");
String uname=rs.getString("userName");
String psw=rs.getString("passWord");
int desigId=rs.getInt("designationId");
System.out.println("User id:" + uId);
System.out.println("UserName:"+ uname);
System.out.println("password:"+psw);
System.out.println("designation:"+ desigId);
}}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException sqle)
{

24
sqle.printStackTrace();
}

25

You might also like