0% found this document useful (0 votes)
8 views

Java Final File

This is the Java Practical file with source code and output screen screen shots and basic theory about each practical.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java Final File

This is the Java Practical file with source code and output screen screen shots and basic theory about each practical.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

1.WAP to multiply two matrices.

importjava.util.Scanner;
classMatrixMultiplication
{
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 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("The matrices can't be multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];

System.out.println("Enter 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 the matrices:");

for (c = 0; c < m; c++)


{
for (d = 0; d < q; d++)
System.out.print(multiply[c][d]+"\t");

System.out.print("\n");
}
}
}
}
2.WAP to check if a number is a palindrome number.
importjava.util.Scanner;
class Palindrome{
public static void main(String args[]){
intr,sum=0,temp;
int n;
Scanner in = new Scanner(System.in);

System.out.println("Enter the number");


n = in.nextInt();

temp=n;
while(n>0){
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
3.WAP to print Floyd's pyramid

importjava.util.Scanner;

public class pattern


{
public static void print(int n)
{
int i, j, num=1;

for(i=0; i<n; i++)


{

for(j=0; j<=i; j++)


{
System.out.print(num+ " ");

num = num + 1;
}

System.out.println();
}
}

public static void main(String args[])


{
int n;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number");
n = in.nextInt();
print(n);

}
}
4.WAP to find the GCD of two numbers
importjava.util.Scanner;
public class GCD {

public static void main(String[] args) {


int num1,num2,gcd = 1;

Scanner in = new Scanner(System.in);


System.out.print("Enter the number 1:");
num1 = in.nextInt();
System.out.print("Enter the number 2:");
num2 = in.nextInt();

for(int i = 1; i <= num1 && i <= num2; i++)


{
if(num1%i==0 && num2%i==0)
gcd = i;
}

System.out.printf("GCD of %d and %d is: %d", num1, num2, gcd);


}

}
5.WAP to find smallest and largest numberin an array of
integers
importjava.util.Scanner;
public class L
{public static void main(String[] args)
{int a[] =new int[10];
Scanner s =new Scanner(System.in);
System.out.println("Enter array elements ");
for(int i=0;i<a.length;i++)
{a[i]=s.nextInt();}
int min = a[0];
int max = a[0];

for (int i = 1; i <a.length; i++)


{if (a[i] > max)
{
max = a[i];
}
if (a[i] < min)
{
min = a[i];
}
}

System.out.println("Largest Number in a given array is : " + max);


System.out.println("Smallest Number in a given array is : " + min);
}

}
6.WAP to count the number of words in a given string
importjava.util.Scanner;
public class N
{
public static void main(String args[])
{

Scanner si =new Scanner(System.in);


System.out.println("Enter String ");
String s = si.nextLine();

int count = 1;

for (int i = 0; i <s.length() - 1; i++)


{
if ((s.charAt(i) == ' ') && (s.charAt(i + 1) != ' '))
{
count++;

}
}
System.out.println("Number of words in a string = " + count);
}
}
7.WAP to calculate the bonus of a programmer by inheriting the
employee class(Single inheritance)

class Employee{

int bonus = 5000;

class Programmer extends Employee{

int salary = 10000;

classBonusInheritance{

public static void main(String[] main){

Programmer p = new Programmer();

int total = p.salary+p.bonus;

System.out.println("The bonus of the programmer is: "+total);

}
8.WAP to show the functionality of super keyword

class Base
{
void message()
{
System.out.println("This is base class");
}
}

class Derived extends Base


{
void message()
{
System.out.println("This is derived class");
}

void display()
{

message();

super.message();
}
}

classsuper_const
{
public static void main(String args[])
{
Derived s = new Derived();

s.display();
}
}
class Base
{
void message()
{
System.out.println("This is base class");
}
}

class Derived extends Base


{
void message()
{
System.out.println("This is derived class");
}

void display()
{

message();

super.message();
}
}

classsuper_method
{
public static void main(String args[])
{
Derived s = new Derived();

s.display();
}
}
9.WAP to show the concept of multiple inheritance using
interfaces
interface I1
{ void show1();
}

interface I2
{ void show2();
}

class M implements I1, I2


{

public void show1()


{
System.out.println("Interface 1 function");
}

public void show2()


{
System.out.println("Interface 2 function");
}
public void show3()
{
System.out.println("Derived class function");
}

public static void main(String args[])


{
M d = new M();
d.show1();
d.show2();
d.show3();
}}

}
10.WAP to compute the volume of cylinder, cuboid and cube using an
overloaded method volume depending upon user's choice.
importjava.util.Scanner;

class VC {

public void volume(int x)


{ System.out.println("Volume of Cube");
System.out.println(x*x*x);

public void volume(int l, intb,int h)


{ System.out.println("Volume of Cuboid");
System.out.println(l*b*h);

public void volume(int r, double h)


{ System.out.println("Volume of Cylinder");
System.out.println(3.14*(r*r)*h);

class O
{
public static void main(String a[])
{
VC s = new VC();
intoption,ex;
do
{
Scanner sc = new Scanner(System.in);
System.out.println("Volume Calculation Menu :");
System.out.println("1.Cube 2.Cuboid 3.Cylinder");
option = sc.nextInt();

switch(option)
{
case 1:s.volume(10); break;
case 2:s.volume(10, 20, 30); break;
case 3:s.volume(10, 20.5); break;
default: System.out.println("Invalid choice");
}
System.out.println("Do you want to continue?1.Yes 2.No");
ex=sc.nextInt();
}while(ex==1);
}
}
11.WAP to show constructor overloading
class Box
{
int width, height, depth;

Box(int w, int h, int d)


{
width = w;
height = h;
depth = d;
}

Box()
{
width = height = depth = 0;
}

Box(intlen)
{
width = height = depth = len;
}

int volume()
{
return width * height * depth;
}
}

public class P
{
public static void main(String args[])
{ Box mybox2 = new Box();
Box mybox3 = new Box(7);
Box mybox1 = new Box(5,10,15);

intvol;

vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
vol = mybox3.volume();
System.out.println(" Volume of mybox3 is " + vol);
}
}
12.WAP to implement wrapper classes and show their functionality
class Q
{
public static void main(String args[])
{ int b = 80;
Integer iobj = new Integer(b);
float c = 16.6f;
Float fobj = new Float(c);
System.out.println("Values of Wrapper objects (printing as objects)");
System.out.println("Integer object intobj: " + iobj);
System.out.println("Float object floatobj: " + fobj);
int iv = iobj;
floatfv = fobj;

System.out.println("Unwrapped values (printing as data types)");

System.out.println("int value : " + iv);


System.out.println("float value : " + fv);

}
}
13.WAP to show method overriding and to show the functionality of
abstract class.

abstract class Base


{
void show() { System.out.println("Base show()"); }
}

class Derived extends Base


{

void show() { System.out.println("Derived show()"); }


}

class Main
{
public static void main(String[] args)
{

Derived obj1 = new Derived();


obj1.show();

}
}
14.WAP for showing NumberFormatException
classNumberE
{
public static void main(String args[])
{
try {

intnum = Integer.parseInt ("jajoo") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception has occur");
}
}
}
15.WAP to implement the concept of exception handling by creating
user defined exception
classMyException extends Exception
{

public class MYE


{

public static void main(String args[])


{
try
{

throw new MyException();


}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
16.WAP to implement the concept of threading by extending
the thread class and show the use of isAlive() and join()
method

isAlive()
public class Thread_alive extends Thread {
public void run()
{
System.out.println("this is ");
try {
Thread.sleep(300);
}
catch (InterruptedExceptionie) {
}
System.out.println("computer ");
}
public static void main(String[] args)
{
Thread_alive c1 = new Thread_alive();
Thread_alive c2 = new Thread_alive();
c1.start();
c2.start();
System.out.println(c1.isAlive());
System.out.println(c2.isAlive());
}
}
Join()
public class Thread_join extends Thread {
public void run()
{
System.out.println("this is ");
try {
Thread.sleep(300);
}
catch (InterruptedExceptionie) {
}
System.out.println("computer ");
}
public static void main(String[] args)
{
Thread_join c1 = new Thread_join();
Thread_join c2 = new Thread_join();
c1.start();

try {
c1.join();
}
catch (InterruptedExceptionie) {
}

c2.start();
}
}
17.WAP to set the thread priorities
importjava.lang.*;

classThread_prio extends Thread


{
public void run()
{
System.out.println("Inside run method");
}

public static void main(String[]args)


{
Thread_prio t1 = new Thread_prio();
Thread_prio t2 = new Thread_prio();
Thread_prio t3 = new Thread_prio();

System.out.println("t1 thread priority : " +


t1.getPriority());
System.out.println("t2 thread priority : " +
t2.getPriority());
System.out.println("t3 thread priority : " +
t3.getPriority());
t1.setPriority(3);
t2.setPriority(6);
t3.setPriority(9);
System.out.println("t1 thread priority : " +
t1.getPriority());
System.out.println("t2 thread priority : " +
t2.getPriority());
System.out.println("t3 thread priority : " +
t3.getPriority());
}
}
18.WAP to show synchronization between the threads
classPr_demo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}

classthr_demo extends Thread {


private Thread t;
private String threadName;
Pr_demo PD;

thr_demo( String name, Pr_demopd) {


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 Thread_syn {

public static void main(String args[]) {


Pr_demo PD = new Pr_demo();

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


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

T1.start();
T2.start();
try {
T1.join();
T2.join();
} catch ( Exception e) {
System.out.println("Interrupted");
}
}
}
19.WAP to show inter thread communication using wait(),
notify() and notifyAll() method
importjava.util.Scanner;
public class threadexample
{
public static void main(String[] args)
throwsInterruptedException
{
final PC pc = new PC();

Thread t1 = new Thread(new Runnable()


{
public void run()
{
try
{ pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace(); }
}
});

Thread t2 = new Thread(new Runnable()


{

public void run()


{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

t1.start();
t2.start();
t1.join();
t2.join();
} public static class PC
{ public void produce()throws InterruptedException
{
synchronized(this)
{
System.out.println("producer thread 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);
}
}
}}
20.WAP using an applet to display a message in the applet
importjava.applet.Applet;
importjava.awt.Graphics;

/*
<applet code="myapplet" width=200 height=160>
</applet>
*/

public class myapplet extends Applet


{
public void paint(Graphics g){
g.drawString("Hello World", 50, 50);
}
}
21.Write a Program to show a moving banner in an applet
importjava.awt.*;
importjava.applet.*;

/* <APPLET code = "banner" width=500 height=500></APPLET> */

public class banner extends Applet implements Runnable {


private String output;
privateintx,y,flag;
Thread t;
public voidinit(){
output = "Moving Banner Text";
x = 100;
y = 100;
flag = 1;
t = new Thread(this, "MyThread");
t.start();
}
public void update(){
x = x + 10*flag;
if(x>300)
flag = -1;
else if(x<100)
flag = 1;
}
public void run(){
while(true){
repaint();
update();
try{
Thread.sleep(500);
}
catch(InterruptedExceptionie){
System.out.println(ie);
}
}
}
public void paint(Graphics g){
g.drawString(output, x, y);
}
}
22.Write a Program to display in the status bar of the applet
window
importjava.awt.Graphics;
importjava.applet.Applet;

/* <APPLET code = "statusDisplay" width = 500 height = 500></APPLET>*/

public class statusDisplay extends Applet{


public void paint(Graphics g){
g.drawString("Hello World", 100, 50);
showStatus("Status Text");
}
}
23.Write a Program to create a window and handle various
mouse events
importjava.awt.*;
importjava.awt.event.*;
public class mouseHandler extends Frame implements MouseListener{
Label l;
mouseHandler(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
} public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
} public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
} public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
} public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
} public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
newmouseHandler();
}
}
24.Write a Program to Use of Adapter Class

KeyAdapter class
importjava.awt.*;
importjava.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l;
TextArea area;
Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
} public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words:"+words.length+" Characters:"+text.length());
} public static void main(String[] args) {
newKeyAdapterExample();
}

}
WindowAdapter class
importjava.awt.*;

importjava.awt.event.*;
public class FirstEventHandling{
Frame f;
FirstEventHandling(){
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
f.dispose();
}
});

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
newFirstEventHandling();
}
}
25.Write a program to draw line, rectangle, eclipse, arc &
polygon in a window & assign different colours to them.

importjava.awt.*;
importjavax.swing.*;
/*
<applet code="ellipse" width=200 height=160>
</applet>
*/
public class ellipse extends JApplet {

public void init()


{ setSize(400, 400);
repaint(); }
public void paint(Graphics g)
{ g.setColor(Color.red);
g.drawOval(100, 100, 150, 100);
g.setColor(Color.blue);
g.drawRect(100, 100, 200, 200);
g.setColor(Color.black);
g.drawLine(10, 20, 30, 40);
int x[] = { 10, 30, 40, 50, 110, 140 };
int y[] = { 140, 110, 50, 40, 30, 10 };
intnumberofpoints = 6;
g.setColor(Color.green);
g.drawPolygon(x, y, numberofpoints);
}
}
26.Write a program to create a student registration form which
includes student name, roll number , age , hobbies (through
checkboxes) , gender (through radio button), school name to be
selected through list & a button showing the summary of the user
selection with any suitable layout used

importjava.awt.*;
/*<html>
<head><title>Register</title></head>
<body>
<applet code="Tes.class" width=230 height=300></applet>
</body>
</html>
*/
public class Tes extends java.applet.Applet
{
public void init()
{

setLayout(new FlowLayout(FlowLayout.LEFT));

add(new Label("Name :"));


add(new TextField(10));

add(new Label("Roll number :"));


add(new TextField(10));

add(new Label("Age :"));


add(new TextField(10));

add(new Label("Gender :"));


CheckboxGroup job = new CheckboxGroup();
add(new Checkbox("Male", job, false));
add(new Checkbox("Female", job, false));

add(new Label("School Name :"));


Choice school = new Choice();
school.addItem("Delhi Public School");
school.addItem("Vishal Bharti Public School");
school.addItem(" BalBharti Public School");
Component add = add(school);
add(new Button("Summary"));

}
}
27.Write a program to implement vector class and its method.
importjava.util.*;
classVector_class {
public static void main(String[] arg)
{

Vector v = new Vector();

v.add(1);
v.add(2);
v.add("Data Structure");
v.add("Algorithm");
v.add(3);

System.out.println("Vector is " + v);


}
}
28.Write a program to show the use of string, string buffer & string
tokenizer.

 string
import java.io.*;
importjava.util.*;
classstring_test
{
public static void main (String[] args)
{
String s= "Data Structure and Algo ";

// or String s= new String ("Data Structure and Algo ");

System.out.println("String length = " + s.length());


}
}

 string buffer
import java.io.*;
classstring_buffer {
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("Data Structure");
s.append("Algorithm");
System.out.println(s);
s.append(1);
System.out.println(s);
}
}
 string tokenizer

importjava.util.*;
public class string_token
{
public static void main(String args[])
{
System.out.println("Using Constructor 1 - ");
StringTokenizer st1 =
newStringTokenizer("AVA : Code : String", " ");
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());

System.out.println("Using Constructor 2 - ");


StringTokenizer st2 =
newStringTokenizer("JAVA : Code : String", " :");
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());

System.out.println("Using Constructor 3 - ");


StringTokenizer st3 =
newStringTokenizer("JAVA : Code : String", " :", true);
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}
29.Write a program to read and write from a file in byte and character
format.

 Byte format

import java.io.*;
public class byte_stream
{
public static void main(String[] args) throws IOException
{
FileInputStreamsourceStream = null;
FileOutputStreamtargetStream = null;

try
{
sourceStream = new FileInputStream("sorcefile.txt");
targetStream = new FileOutputStream ("targetfile.txt");

int temp;
while ((temp = sourceStream.read()) != -1)
targetStream.write((byte)temp);
}
finally
{
if (sourceStream != null)
sourceStream.close();
if (targetStream != null)
targetStream.close();
}
}
}

import java.io.*;
 character format.

public class character_str


{
public static void main(String[] args) throws IOException
{
FileReadersourceStream = null;
try
{
sourceStream = new FileReader("test.txt");

.
int temp;
while ((temp = sourceStream.read()) != -1)
System.out.println((char)temp);
}
finally
{

if (sourceStream != null)
sourceStream.close();
}
}

}
IT-252
Java Programming
Practical File
GURU GOBIND SINGH
INDRAPRASTHA UNIVERSITY

SUBMITTED TO: SUBMITTEDBY:


Mr.BalaKrishna Deepanshu Chauhan
USICT, GGSIPU B.Tech IT (4thSem)
Roll No: 50216401517
INDEX
S.NO PROGRAME NAME DATE SIGN
1. Write a Program to Multiply two
Matrices

2. Write a Programto check if a number is a


palindrome number

3. Write a Programto print Floyd's pyramid

4. Write a Programto find the GCD of two


numbers

5. Write a Programto find smallest and


largest numbering an array of integers

6. Write a Programto count the number of


words in a given string

7. Write a Programto calculate the bonus of


a programmer by inheriting the
employee class(Single inheritance)
8. Write a Programto show the
functionality of super keyword

9. Write a Programto show the concept of


multiple inheritance using interfaces

10. Write a Program to compute the volume


of cylinder, cuboid and cube using an
overloaded method volume depending
upon user's choice
11. Write a Programto show constructor
overloading

12. Write a Programto implement wrapper


classes and show their functionality
13. Write a Programto show method
overriding and to show the functionality
of abstract class
14. Write a Program to show Number
Format Exception
15. Write a Program to implement the
concept of exceptional handling by
creating user defined exceptions
16. Write a Programto implement the
concept of threading by extending the
thread class and show isAlive() and
join() method
17. Write a Programto set the thread
properties
18. Write a Programto show sync between
the threads
19. Write a Programto show inter-thread
communication method, notify method,
notifyAll method
20. Write a Programusing an applet to
display a message in the applet
21. Write a Programto show a moving
banner in an applet
22. Write a Programto display in the status
bar of the applet window
23. Write a Programto create a window and
handle various mouse events
24. Write a Programto Use of Adapter Class
25. Write a program to draw line, rectangle,
eclipse, arc & polygon in a window &
assign different colours to them.
26. Write a program to create a student
registration form which includes student
name, roll number , age , hobbies
(through checkboxes) , gender (through
radio button), school name to be selected
through list & a button showing the
summary of the user selection with any
suitable layout used

27. Write a program to implement vector


class and its method.

28. Write a program to show the use of


string, string buffer & string tokenizer.

29. Write a program to read and write from


a file in byte and character format.

You might also like