Upload
others
View
2
Download
1
Embed Size (px)
Citation preview
S.S Vasava 140220107117
Practical – 12 Write a method for computing xy by doing repetitive multiplication. x
and y are of type integer and are to be given as command line
arguments. Raise and handle exception(s) for invalid values of x and y.
Also define method main. Use finally in above program and explain its
usage.
class Practical_12
{
public static int mul(int x, int y)
{
if(x == 0 || y == 0)
{
return 0;
}
else if(y>0)
{
return x + mul(x,y-1);
}
return -mul(x,-y);
}
public static void main(String []args)
{
int x,y;
try
{
x = Integer.parseInt(args[0]);
y = Integer.parseInt(args[1]);
System.out.println(x+"*"+y+" = "+mul(x,y));
}
S.S Vasava 140220107117 catch(NumberFormatException e)
{
System.out.println("Exception : "+e);
}
finally
{
System.out.println("Executes whether exception occurs or not.");
}
}
}
S.S Vasava 140220107117
Practical – 13 Write a program to handle NoSuchMethodException,
ArrayIndexOutofBoundsException using try-catch-finally and throw.
import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Method;
public class ExceptionTest
{
public ExceptionTest()
{ }
private void testNoSuchMethodException() throws NoSuchMethodException
{
Class c;
try
{
c=Class.forName("java.lang.String");
try
{
Class[] paramType=new Class[5];
Method m=c.getDeclaredMethod("fooMethod",paramType);
}
catch(SecurityException e)
{
e.printStackTrace();
}
catch(NoSuchMethodException e)
S.S Vasava 140220107117 {
e.printStackTrace();
throw e;
}
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
private void testArrayOutOfBoundException()
{
List nameList=new ArrayList();
nameList.add("Practical_13");
try
{
nameList.get(1);
}
catch(ArrayIndexOutOfBoundsException ex)
{
ex.printStackTrace();
}
}
public static void main(String args[])
{
ExceptionTest obj=new ExceptionTest();
try
S.S Vasava 140220107117 {
obj.testNoSuchMethodException();
}
catch(NoSuchMethodException e)
{ }
obj.testArrayOutOfBoundException();
}
}
S.S Vasava 140220107117
Practical – 14 Write a program to handle InterruptedException,
IllegalArgumentException using try-cat-finally and throw.
InterruptedException
//file1: Save as SampleThread.java and compile.
import java.util.concurrent.TimeUnit;
public class SampleThread extends Thread {
public SampleThread() {
super();
System.out.println("An instance of the " +
SampleThread.class + " class was created!");
}
public void run() {
try {
/* Sleep for some seconds. */
TimeUnit.SECONDS.sleep(10);
}
catch(InterruptedException ex) {
System.err.println("An InterruptedException was
caught: " + ex.getMessage());
}
}
}
//file 2: Save InterruptedExceptionExample.java the compile this file and run.
public class InterruptedExceptionExample {
S.S Vasava 140220107117 public static void main(String[] args) throws InterruptedException {
// Create a new thread.
Thread thread = new SampleThread();
//Start the thread's execution.
thread.start();
//Interrupt the thread.
thread.interrupt();
//Join the thread.
thread.join();
}
}
IllegalArgumentExceptionExample
import java.io.File;
public class IllegalArgumentExceptionExample {
public static String createRelativePath(String parent, String filename) {
if(parent == null)
throw new IllegalArgumentException("The parent path cannot be null!");
if(filename == null)
S.S Vasava 140220107117 throw new IllegalArgumentException("The filename cannot be null!");
return parent + File.separator + filename;
}
public static void main(String[] args) {
// The following command will be successfully executed.
System.out.println(IllegalArgumentExceptionExample.createRelativePath("dir1", "file1"));
System.out.println();
// The following command throws an IllegalArgumentException.
System.out.println(IllegalArgumentExceptionExample.createRelativePath(null, "file1"));
}
}
S.S Vasava 140220107117
Practical – 15 Write a program that generates custom exception if any integer value
given from its command line arguments is negative.
public class Practical_15{
public static void main(String args[]){
try{
int num = Integer.parseInt(args[0]);
if(num<0)
System.out.println("The given number is negative.");
}
catch(NumberFormatException e){
System.out.println("Your input is not a number");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Please enter a number on the command line");
}
}
}
S.S Vasava 140220107117
Practical – 16 Write a java program which read numbers from number.txt file and
store even number to even.txt and odd number into odd.txt file.
import java.io.*;
import java.util.*;
public class FileExample {
public static void main(String[] args) throws IOException {
try {
FileOutputStream outputStreamEven = new FileOutputStream("D:/Java Programs/Program from
12/Practical_16/even.txt");
FileOutputStream outputStreamOdd = new FileOutputStream("D:/Java Programs/Program from
12/Practical_16/odd.txt");
DataOutputStream wodd = new DataOutputStream(outputStreamOdd);
DataOutputStream weven = new DataOutputStream(outputStreamEven);
File file = new File("D:/Java Programs/Program from 12/Practical_16/number.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext())
{
if (scanner.hasNextInt())
{
integers.add(scanner.nextInt());
}
else
{
scanner.next();
}
}
System.out.println(integers);
S.S Vasava 140220107117 for(Integer i : integers)
{
if (i % 2 != 0) {
wodd.writeInt(i);
}
else {
weven.writeInt(i);
}
}
}finally{}
}
}
S.S Vasava 140220107117
Practical – 17 Write a program to check that whether the name given from command
line is file or not? If it is a file then print the size of file and if it is
directory then it should display the name of all files in it.
import java.io.*;
class Practical_17
{
public static void main(String[] args) {
String fname =args[0];
File f = new File(fname);
System.out.println("File name :"+f.getName());
System.out.println("Exists :"+f.exists());
if(f.exists())
{
System.out.println("Path: "+f.getPath());
System.out.println("Absolute path:" +f.getAbsolutePath());
System.out.println("Parent:"+f.getParent());
System.out.println("Is a file:"+f.isFile());
System.out.println("Is writeable:"+f.canWrite());
System.out.println("Is readable:"+f.canRead());
System.out.println("File Size in bytes "+f.length());
if(f.isDirectory())
{
File[] contentsOfDirectory=f.listFiles();
System.out.println("Is a directory:"+f.isDirectory());
for(File obj : contentsOfDirectory) {
if(obj.isFile()) {
System.out.println("File name is "+obj.getName());
}
S.S Vasava 140220107117 else if(obj.isDirectory()) {
System.out.println("Directory name is "+obj.getName());
}
}
}
}
}
}
S.S Vasava 140220107117
Practical – 18 Write a Java program to copy content of file1.txt to file2.txt using Java
file handling.
import java.io.*;
class Practical_18{
public static void main(String args[]) {
try (FileReader fr = new FileReader("file1.txt");
FileWriter fw = new FileWriter("file2.txt")) {
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
S.S Vasava 140220107117
Practical – 19 Write a program to replace all “word1” by “word2” from a file1, and
output is written to file2 file and display the no. of replacement.
import java.io.*;
class Practical_19
{
public static void main(String args[])
{
try
{
FileReader f1 = new FileReader("file1.txt");
BufferedReader br = new BufferedReader(f1);
FileWriter f2 = new FileWriter("file2.txt");
String word1,word2;
BufferedReader b2 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter word 1:");
word1 = b2.readLine();
System.out.println("Enter word 2:");
word2 = b2.readLine();
String x="",msg="";
while((x=br.readLine())!=null)
{
//msg=x;
msg+=x+"";
}
f1.close();
msg = msg.replace(word1,word2);
f2.write(msg);
S.S Vasava 140220107117
Practical – 20 Write a program that counts number of characters, words,
and lines in a file. Use exceptions to check whether the file
that is read exists or not.
Import java.io.*;
public class Test
{
public static void main(String[] args) throws IOException
{
File file = new File("File1.txt");
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
String line;
int countWord = 0;
int sentenceCount = 0;
int characterCount = 0;
while((line = reader.readLine()) != null)
{
if(!(line.equals("")))
{
characterCount += line.length();
String[] wordList = line.split("\\s+");
countWord += wordList.length;
String[] sentenceList = line.split("[!?.:]+");
S.S Vasava 140220107117
sentenceCount += sentenceList.length;
}
}
System.out.println("Total word count
= " + countWord);
System.out.println("Total number of
sentences = " + sentenceCount);
System.out.println("Total number of
characters = " + characterCount);
}
}
S.S Vasava 140220107117
Practical – 21
Write an application that read limit from user and executes
two threads. One thread displays total of first n even numbers
& another thread displays total of first n odd numbers.
public class OddEvenThread
{
public static void main(String args[])
{
OddEven o1=new OddEven("Odd Number " ,1);
OddEven o2=new OddEven("Even Number " ,2);
o1.start();
o2.start();
}
}
class OddEven extends Thread
{
private int number;
public OddEven(String name,int p_number)
{
super(name);
this.number=p_number;
}
public void run()
{
for(int i=0;i<5;i++)
{
S.S Vasava 140220107117
Practical – 22
Write a Program Thread Priority.
class display implements Runnable
{
public void run()
{
int i=0; while(i<3)
System.out.println(i++);
}
}
public class ThreadPriority
{
public static void main(String args[])
{
display d=new display(); Thread t1=new Thread(d); Thread t2=new Thread(d); Thread t3=new Thread(d);
System.out.println("Current Priority:"+t1.getPriority()); t1.setPriority(3);
t1.start();
S.S Vasava 140220107117 t2.start();
t3.start();
System.out.println("New Priority:"+t1.getPriority());
}
}
S.S Vasava 140220107117
Practical – 23
Write a program for Inter Thread communication in java.
import java.util.Scanner;
public class threadexample
{
public static void main(String[] args)throws InterruptedException
{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
}
pc.produce();
catch(InterruptedException e)
{
}
});
e.printStackTrace();
}
S.S Vasava 140220107117
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
}
pc.consume();
catch(InterruptedException e)
{
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
e.printStackTrace();
}
public static class PC
{
public void produce()throws InterruptedException
{
synchronized(this)
{
System.out.println("producer thread
S.S Vasava 140220107117
running"); wait();
System.out.println("Resumed");
}
}
public void consume()throws InterruptedException
{
Thread.sleep(1000);
Scanner s = new Scanner(System.in);
synchronized(this)
{
System.out.println("Waiting for return
key."); s.nextLine();
System.out.println("Return key
pressed"); notify();
Thread.sleep(2000);
}
}
}
}
S.S Vasava 140220107117
Practical – 24
Write a Java Program to print IP address of a given URL.
import java.net.*;
class Addr
{
public static void main(String args[])
{
try
{
}
InetAddress in=InetAddress.getByName("www.google.com");
System.out.println("The ip Address of site is:"+in.getHostAddress());
catch(Exception e)
{
System.out.println("Some Exception has occurred
with details"+e.getMessage());
}
}
}
S.S Vasava 140220107117
Practical – 25
Write a java program to send no from client and server response with
reverse number.
ContentsClient.java
import java.net.*; import java.io.*;
public class ContentsClient
{
public static void main( String args[ ] ) throws Exception
{
Socket sock = new Socket( "127.0.0.1",
4000);
System.out.print("Enter the file name"); BufferedReader keyRead = new
BufferedReader(new
InputStreamReader(System.in)); String fname = keyRead.readLine();
OutputStream ostream = sock.getOutputStream( ); PrintWriter pwrite = new
PrintWriter(ostream, true); pwrite.println(fname); InputStream istream =
sock.getInputStream();
BufferedReader socketRead = new BufferedReader(new InputStreamReader(istream));
String str;
while((str = socketRead.readLine()) != null)
{
System.out.println(str);
}
S.S Vasava 140220107117 pwrite.close();
socketRead.close(); keyRead.close();
}
}
ContentsServer.java import java.net.*; import java.io.*;
public class ContentsServer
{
public static void main(String args[]) throws Exception
{
ServerSocket sersock = new ServerSocket(4000); System.out.println("Server ready for
connection"); Socket sock = sersock.accept();
System.out.println("Connection is successful and wating for chatting"); InputStream
istream = sock.getInputStream( );
BufferedReader fileRead =new BufferedReader(new InputStreamReader(istream));
String fname = fileRead.readLine( );
BufferedReader contentRead = new BufferedReader(new FileReader(fname) );
OutputStream ostream = sock.getOutputStream( );
PrintWriter pwrite = new PrintWriter(ostream, true); String str;
while((str = contentRead.readLine()) != null)
S.S Vasava 140220107117
{
pwrite.println(str);
}
sock.close(); sersock.close(); pwrite.close(); fileRead.close(); contentRead.close();
}
S.S Vasava 140220107117
Practical - 26
Write a subroutine to exchange two 8-bit numbers. Use it to reverse an
array of 8-bit numbers.
import java.io.*; class ReverseArray
{
static void rvereseArray(int arr[], int start, int end)
{
int temp;
if (start >= end)
return; temp = arr[start];
arr[start] = arr[end]; arr[end] = temp;
rvereseArray(arr, start+1, end-1);
}
static void printArray(int arr[], int size)
{
for (int i=0; i < size; i++) System.out.print(arr[i] + " ");
System.out.println("");
}
public static void main (String[] args)
S.S Vasava 140220107117
{
int arr[] = {1, 2, 3, 4, 5, 6};
printArray(arr, 6);
rvereseArray(arr, 0, 5); System.out.println("Reversed array is "); printArray(arr, 6);
}
}
S.S Vasava 140220107117
Practical – 27
Write a java program two way chat application in java.
GossipClient.java import java.io.*; import java.net.*;
public class GossipClient
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("127.0.0.1", 3000);
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
OutputStream ostream = sock.getOutputStream(); PrintWriter pwrite = new
PrintWriter(ostream, true); InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Start the chitchat, type and press Enter key"); String receiveMessage,
sendMessage; while(true)
{
sendMessage = keyRead.readLine(); pwrite.println(sendMessage); pwrite.flush();
if((receiveMessage = receiveRead.readLine()) != null)
{
S.S Vasava 140220107117
System.out.println(receiveMessage);
}
}
}
}
GossipServer.java import java.io.*; import java.net.*;
public class GossipServer
{
public static void main(String[] args) throws Exception
{
ServerSocket sersock = new ServerSocket(3000); System.out.println("Server
ready for chatting"); Socket sock = sersock.accept( );
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true); InputStream istream =
sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage, sendMessage; while(true)
{
S.S Vasava 140220107117 if((receiveMessage = receiveRead.readLine()) != null)
System.out.println(receiveMessage);
}
sendMessage = keyRead.readLine(); pwrite.println(sendMessage); pwrite.flush();
}
}
}
S.S Vasava 140220107117
Practical – 28
Prepare a class diagram for given group of classes using multiplicity,
generalization, association concepts. And add at least 5-7 attributes and
3-5 operations for particular class Page, Shape, Point, Line, Arc, Ellipse,
Rectangle, Circle.
S.S Vasava 140220107117
Practical – 29
Prepare a class diagram for given group of classes using multiplicity,
generalization, association concepts. And add at least 5-7 attributes and
3-5 operations for particular class. City, Airport, Airline, Pilot, Flight,
Plane, Seat, Passenger.
S.S Vasava 140220107117
Practical – 30
Prepare a state diagram for an interactive diagram editor for selecting
and dragging objects.
S.S Vasava 140220107117
Practical – 31
Prepare a use case diagram and sequence diagram for a computer email
system.
Use Case
S.S Vasava 140220107117
Practical – 32
Prepare an activity diagram for computing a restaurant bill, there
should be charge for each delivered item. The total amount should be
subject to tax and service charge of 18% for group of six and more. For
smaller groups there should be a blank entry. Any coupons or gift
certificates submitted by the customer should be subtracted.