Vous êtes sur la page 1sur 21

Programming in Java Lab

Prepared by
Padma Lochan Pradhan, citrprcs@rediffmail.com
Dept of Computer Science & Engineering
Central Institute of Technology, New Raipur, CG, India

Branch: Computer Science & Engineering Semester: V


Subject: Programming in Java Laboratory
Code: 322562(22)
Maximum Marks: 40 Minimum Marks: 20

No 1. Java program to check armstrong number


import java.util.Scanner;
class ArmstrongNumber
{
public static void main(String args[])
{
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong
number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
}

1. Write a program to sort a stream of Strings.


StringSortingTest.java
package com.javaforecast4u;
public class StringSortingTest {
public static void main(String args[])
{
String
StringArray[]={"java","fore","cast","for","you"};
int n=StringArray.length;
String temp;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(StringArray[i].compareTo(StringArray[j])>0)
{
temp=StringArray[i];
StringArray[i]=StringArray[j];
StringArray[j]=temp;
}
}
}
for(int i=0;i<n;i++)
{
System.out.println(StringArray[i]);
}
}
}

2. Write a program to perform multiplication of two matrices.


import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first
matrix");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();
System.out.println("Enter the number of rows and columns of second
matrix");
p = in.nextInt();
q = in.nextInt();
if ( n != p )
System.out.println("Matrices with entered orders can't be
multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = in.nextInt();
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}

}
System.out.println("Product of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
}
}
}
}

3. Write a program to find the volume of a box having its side w,


h, d means width, height and depth. Its volume is v=w*h*d and
also find the surface area given by the formula =2(wh+hd+dw),
use appropriate constructors for the above.
class Box {
double width;
double height;
double depth;
Box ( double w, double h, double d) {
width = w;
height = h;
depth = d;
}
class Box{
double width;

double height;
double depth;
Box ( double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1;
height = -1;
depth = -1;
}
Box (double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main (String args[]) {
Box mybox1 = new Box(10, 20,15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(Volume of mybox1 is + vol);

vol = mybox2.volume();
System.out.println(Volume of mybox2 is + vol);
vol = mycube.volume();
System.out.println(Volume of mycube is + vol);

4. Develop a program to illustrate a copy constructor so that a


string may be duplicated into another variable either by
assignment or copying.
int a = new Integer(5);
int b = a;
b = b + b;
System.out.println(a); // 5 as expected
System.out.println(b); // 10 as expected

assumed a similar thing for objects. Consider this class.


public class SomeObject {
public String text;

public SomeObject(String text) {


this.setText(text);
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

5. Create a base class called shape. It contains two methods


getxyvalue() and showxyvalue() for accepting co-ordinates
and to display the same. Create the subclass called Rectangle
which contains a method to display the length and breadth of
the rectangle called showxyvalue().Use overriding concept.
public class rectangle {
// Private variables
private int width;
private int height;
private int x;
private int y;
// Our constructor for building the rectangle
public rectangle(int xcoord, int ycoord, int thewidth, int
theheight) {
}
// Get the rectangle's width
public int getWidth() {
return width;
}
}

6.

Write a program that creates an abstract class called


dimension, creates two subclasses, rectangle and triangle.
Include appropriate methods for both the subclass that
calculate and display the area of the rectangle and triangle.

Abstract Class : Shape

dim1, dim2, disp( )


abstract area ( )

Class: Rectangle
getd( ), area ( )

Class: Rectangle
getd( ), area ( )
import java.lang.*;
import java.io.*;
abstract class Shape
{
int dim1,dim2;
void getd()throws IOException
{
BufferedReader br = new BufferedReader (new
InputStreamReader(System.in));
System.out.println ("Enter Value of 1st Dimension");
dim1=Integer.parseInt(br.readLine());

System.out.println ("Enter Value of 2nd Dimension");


dim2=Integer.parseInt(br.readLine());
}
abstract void area();
}
class Rectangle extends Shape
{
void getd() throws IOException
{
super.getd();
}
void area()
{
int a=dim1*dim2;
System.out.println ("Area of Rectangle = "+a);
}
}
class Triangle extends Shape
{
void getd() throws IOException
{
super.getd();
}
void area()

{
double b=(1*dim1*dim2)/2;
System.out.println ("Area of Triangle = "+b);
}
}
class q11MethodOverriding
{
public static void main(String args[]) throws IOException
{
Rectangle R = new Rectangle();
R.getd();
R.area();
Triangle T = new Triangle();
T.getd();
T.area();
}
}

7. Write a program which throws Arithmetic Exception. Note the


output; write another class (in a different file) that handles the
Exception.
import java.io.* ;
public class FinallyPractice1
{
public static void main(String [])
{
BufferedReader stdin=new BufferedReader(new
InputStreamReader(System.in));
String inData; int num=0, div=0;
try
{

System.out.println("Enter the numerator:");


inData=stdin.readLine();
num=Integer.parseInt(inData);

System.out.println("Enter the divisor:");


inData=stdin.readLine();
div=Integer.parseInt(inData);

System.out.println(num+"/"+div+"

is

"+(num/div));

}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println("You can't divide "+ num + " by " + div);
}
catch(ArithmeticException aex)
{
System.out.println("You entered not a number: " + inData);
}
finally

{
System.out.println("If the division didn't work, you entered bad
data.");
}
System.out.println("Good-by");
}

8. Create a user defined Exception class which throws


Exception when the user inputs the marks greater than 100.
public class Lab6
{
public static void main(String[] args)throws IOException,
NullPointerException, ArrayIndexOutOfBoundsException
{
//the memory with 100 elements
int[] vMem = new int[100];
//the memory with 1000 elements
int[][] vTopMem = new int[1000][];
vTopMem[0] = vMem;
System.out.println("Enter an integer: ");
File vMemory = new File("file name and location");
RandomAccessFile storeMem = new RandomAccessFile(vMemory, "rw");
Scanner input = new Scanner(System.in);
while(true)
{
for(int i = 0; i < vMem.length; i++)
{
vMem[i] = input.nextInt();
storeMem.write(i);
if(i > vMem.length)

{
System.out.println("out of bounds!");
}
}
}
}

9. Write a program in which a Mythread class is created by


extending the Thread class. In another class, create objects of
the Mythread class and run them. In the run method print
CSVTU 10 times. Identify each thread by setting the name.
//This class is made as a thread by extending "Thread" class.
public class FirstThread extends Thread
{
//This method will be executed when this thread is executed
public void run()
{

//Looping from 1 to 10 to display numbers from 1 to 10


for (int i=1; i<=10; i++)
{
//Displaying the numbers from this thread
System.out.println( "Messag from First Thread : " +i);

/*taking a delay of one second before displaying next number


*
* "Thread.sleep(1000);" - when this
* this thread will sleep for 1000

statement is executed,

milliseconds (1 second)

* before executing the next statement.


*

* Since

we are making this thread to sleep for one second,

* we need to handle

"InterruptedException". Our thread

* may throw this exception if it is

interrupted while it

* is sleeping.
*
*/
try
{
Thread.sleep(1000);
}
catch (InterruptedException

interruptedException)

{
/*Interrupted exception will be thrown when a sleeping or

waiting

* thread is interrupted.
*/
System.out.println(
+interruptedException);

"First Thread is interrupted when it is

}
}
}
}
//This class is made as a thread by extending "Thread" class.

public class SecondThread extends Thread


{

//This method will be executed when this thread is executed


public void run()
{
//Looping from 1 to 10 to display numbers from 1 to 10

sleeping"

for (int i=1; i<=10; i++)


{
System.out.println( "Messag from Second Thread : " +i);
/*taking a delay of one second before displaying next number
* "Thread.sleep(1000);" - when this statement is executed,
* this thread will sleep for 1000 milliseconds (1 second)
* before executing the next statement.
*
* Since we are making this thread to sleep for one second,
* we need to handle "InterruptedException". Our thread
* may throw this exception if it is interrupted while it
* is sleeping.
*/
try
{
Thread.sleep (1000);
}
catch (InterruptedException interruptedException)
{
/*Interrupted exception will be thrown when a sleeping or waiting
*thread is interrupted.
*/
System.out.println( "Second Thread is interrupted when it is sleeping"
+interruptedException);
}
}
}
}

10.
Write a program using InetAddress class and also show
the utility of URL and URL Connection classes.
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws
UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("starwave.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}

11.
Write a program which illustrates capturing of Mouse
Events. Use Applet class for this.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Mouse" width=500 height=500>
</applet>
*/
public class Mouse extends Applet
implements MouseListener,MouseMotionListener
{
int X=0,Y=20;
String msg="MouseEvents";
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.black);
setForeground(Color.red);
}
public void mouseEntered(MouseEvent m)
{
setBackground(Color.magenta);
showStatus("Mouse Entered");
repaint();
}
public void mouseExited(MouseEvent m)
{
setBackground(Color.black);
showStatus("Mouse Exited");
repaint();
}
public void mousePressed(MouseEvent m)
{
X=10;
Y=20;
msg="NEC";
setBackground(Color.green);
repaint();
}
public void mouseReleased(MouseEvent m)
{
X=10;
Y=20;
msg="Engineering";
setBackground(Color.blue);
repaint();
}
public void mouseMoved(MouseEvent m)
{
X=m.getX();
Y=m.getY();
msg="College";
setBackground(Color.white);
showStatus("Mouse Moved");

repaint();
}
public void mouseDragged(MouseEvent m)
{
msg="CSE";
setBackground(Color.yellow);
showStatus("Mouse Moved"+m.getX()+" "+m.getY());
repaint();
}
public void mouseClicked(MouseEvent m)
{
msg="Students";
setBackground(Color.pink);
showStatus("Mouse Clicked");
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}

12.
Write a program using RMI in which a simple remote
method is implemented.
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class HelloImpl extends UnicastRemoteObject implements Hello
{
public HelloImpl() throws RemoteException {}
public String sayHello() { return "Hello world!"; }
public static void main(String args[])
{
try
{
HelloImpl obj = new HelloImpl();
// Bind this object instance to the name "HelloServer"
Naming.rebind("HelloServer", obj);
}
catch (Exception e)
{
System.out.println("HelloImpl err: " + e.getMessage());
e.printStackTrace();
}
}
}

13.
Write a servlet program using HttpServlet class. Also
give the appropriate HTML file which posts data to the servlet.
public HttpServlet getServletForURI(String uri) throws ServletException,
IOException {
for ( DispatchVector d : _registry) {
if (d._urlPattern.matcher(uri).matches()) {
HttpServlet servlet=loadServlet(d._className);
if (servlet != null) {
return servlet;
}
}
}
return null;
}

14.

Write a JDBC program for Student Mark List Processing.

JDBCSample.java
import java.sql.*;

public class JDBCSample {

public static void main( String args[]) {

String connectionURL =
"jdbc:postgresql://localhost:5432/movies;user=java;password=sample
s";
// Change the connection string according to your db, ip, username
and password

try {
// Load the Driver class.
Class.forName("org.postgresql.Driver");
// If you are using any other database then load the right
driver here.
//Create the connection using the static getConnection method
Connection con = DriverManager.getConnection (connectionURL);
//Create a Statement class to execute the SQL statement

//Execute the SQL statement and get the results in a Resultset


ResultSet rs = stmt.executeQuery("select moviename,
releasedate from movies");

// Iterate through the ResultSet, displaying two values


// for each row using the getString method
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") +
" Date= " + rs.getString("releasedate"));
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the connection

15.
Design a text editor which is having some of the features
con.close();
of} notepad.
}

HTML+KITS

http://freeware.intrastar.net/textedit.htm
}

Vous aimerez peut-être aussi