Oops (Java) Lab Programs-2 PDF
Oops (Java) Lab Programs-2 PDF
(AUTONOMOUS)
REGISTER NUMBER
CERTIFICATE
This is to Certify that this is the bonafide record of work done by
Mr./Miss………………………………………………………………………………
……Of………………………………………year,M.C.A……………………...…….
year………………….
i
INDEX
ii
S.No Date Name of the Experiment Page. No Awarded Signature
Marks
iii
35
WJAP for life cycle of thread 55-57
iv
1. Write a java program to display simple messages on screen .
class manoj
{
public static void main(String args[])
{
System.out.println("hello ");
System.out.println("welcome to java world ");
System.out.println("a very good morning "); manoj
obj=new manoj();
obj.add(2,7);
}
int result;
OUTPUT :
hello
welcome to java world a very
good morning result is 9
1
2. Write a java program to Print integers
class Integers {
public static void main(String[] arguments) {
int c; //declaring a variable
2
3. Write a java program to If else control instructions.
class Condition {
public static void main(String[] args) {
boolean learning = true;
if (learning) {
System.out.println("Java programmer");
}
else {
System.out.println("What are you doing here?");
}
}
}
Output:
3
4. Write a java program to Command line arguments.
class Arguments {
public static void main(String[] args) {
for (String t: args) {
System.out.println(t);
}
}
}
OUTPUT :
4
5. Write a java program for loop to print first 10 natural numbers, i.e., from 1 to 10.
Output of program:
5
6. Write a java program to while loop example
import java.util.Scanner;
class WhileLoop {
public static void main(String[] args) {
int n;
System.out.println("Out of loop");
}
}
Output of program:
6
7. Write a java program Odd even program in Java
import java.util.Scanner;
class OddOrEven
{
public static void main(String args[])
{
int x;
System.out.println("Enter an integer to check if it's odd or even");
Scanner in = new Scanner(System.in);
x = in.nextInt();
if (x % 2 == 0)
System.out.println("The number is even.");
else
System.out.println("The number is odd.");
}
}
Output of program:
7
8. Write a java program to Swapping
import java.util.Scanner;
class SwapNumbers
{
public static void main(String args[])
{
int x, y, t;
System.out.println("Enter two numbers (x & y)");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
t = x;
x = y;
y = t;
Output of program:
8
9. Write a java program to Factorial of a number in Java
import java.util.Scanner;
class Factorial
{
public static void main(String args[])
{
int n, c, f = 1;
n = in.nextInt();
if (n < 0)
System.out.println("Number should be non-negative.");
else
{
for (c = 1; c <= n; c++)
f = f*c;
Output of program:
9
10. Write a java program to Date and Time program in Java
import java.util.*;
class GetCurrentDateAndTime
{
public static void main(String args[])
{
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
Output of program:
10
11. Write a java program to Bubble sort program in Java
import java.util.Scanner;
class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);
OUTPUT :
11
12
12. write a java program to find largest of three numbers
class greater
{
public static void main(String args[])
{
int a=98,b=87,c=99; if(a>b)
{
if(a>c)
{
else
{
if(b>c)
}
else
{
13
}
}
}
}
OUTPUT :
c is greater
14
13. write a java program using classes and object in java
public data()
{
id="8043";
name="MANOJ";
age="22";
}
public void displaydata()
{
System.out.println("my id is="+id);
System.out.println("my name is="+name);
System.out.println("my age is="+age);
}
public static void main(String args[])
{
data obj=new data();
obj.displaydata();
}
}
OUTPUT :
my id is=8043
my name is=MANOJ
my age is=22
15
14. write a java program to implement inheritance
class room
{
int l;
int b;
room(int x, int y)
{
l=x;
b=y;
}
int area()
{
return(l*b);
}
}
class bedroom extends room
{
int h;
bedroom(int x,int y, int z)
{
super(x,y);
h=z;
}
int volume()
{
return(l*b*h);
}
}
class inheritance
{
public static void main(String args[])
{
bedroom room1=new bedroom(10,20,30);
int area1=room1.area();
int volume1=room1.volume();
System.out.println("area1="+area1);
System.out.println("volume1="+volume1);
}
}
OUTPUT :
16
area1=200
volume1=6000
17
new C().start();
}
}
OUTPUT :
from thread A :i= 1
from thread A :i= 2
from thread A :i= 3
from thread A :i= 4
from thread A :i= 5
from thread B :i= 1
from thread B :i= 2
from thread B :i= 3
from thread B :i= 4
from thread B :i= 5
from thread C :i= 1
from thread C :i= 2
from thread C :i= 3
from thread C :i= 4
from thread C :i= 5
18
16. write a java program to implement method overriding
class sup
{
int x;
sup(int x)
{
this.x=x;
}
void display()
{
System.out.println("x= "+x);
}
}
class overloading
{
public static void main(String args[])
{
sub s=new sub(10,20);
s.display();
}
}
19
OUTPUT :
x= 10
y= 20
20
17. write a java program to implement method overloading
class funcload
{
public static void main(String args[])
{
funcload obj=new funcload();
obj.add(15,24);
obj.add(2.3f,0.8f);
obj.add(56,76.76f);
}
int x,y;
float p,q,result;
void add(int a,int b)
{
x=a;
y=b;
result=x+y;
System.out.println("the result is:" + result);
}
void add(float a,float b)
{
p=a;
q=b;
result=p+q;
System.out.println("the result is:" + result);
}
void add(int a,float b)
{
x=a;
p=b;
result=x+p;
System.out.println("the result is:" + result);
}
}
21
OUTPUT :
the result is:39.0
the result is:3.1
the result is:132.76001
interface area
{
final float p=3.14f;
float compute(float x,float y);
}
class rectangle implements area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class circle implements area
{
public float compute(float x,float y)
{
return(p*x*x);
}
}
class inter
{
public static void main(String args[])
{
"+a.compute(10,20));
OUTPUT :
22
19 .write a java program to implement exception handling in java
class handle
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x;
int y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a/(b+c);
System.out.println("y="+y);
}
}
OUTPUT :
Division by zero
y=1
23
20. A Java program that uses both recursive and non-recursive functions to print the nth value of the
Fibonacci sequence .
import
java.util.Scanner;
class _2Assignment
{
public static void main(String args[])
{
System.out.println("Enter the number n to print the faboniccs series ");
Scanner ob=new Scanner(System.in);
short a=ob.nextShort();
Series ob1=new Series();
long b=ob1.input(a);
System.out.println("The "+a+"th number of the faboniccs series is "+b);
}
}
class Series
{
int a=1;
int b=1;
int c=0;
int count;
int input(int a)
{
count=a;
count=fabo(count);
return count;
}
OUTPUT :
24
Enter the number n to print the faboniccs series 8
25
21. A Java program to demonstrate wrapper classes and to fix the precision.
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj); System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Printing primitives
System.out.println("---Printing primitive values---");
26
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}
OUTPUT :
27
22. A Java program that prompts the user for an integer and then prints out all prime numbers up
to that integer.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
n=s.nextInt();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
OUTPUT:
Enter a number:
20
11
13
17
19
28
23. Write a java program to Whether check the given string is Palindrome or
not.(ex:MALAYALAM)
import java.util.Scanner;
class ChkPalindrome
System.out.println("Enter a string:");
str = sc.nextLine();
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
29
}
OUTPUT:
Enter a string:
MALAYALAM
MALAYALAM is a palindrome
30
24. write a java program to sorting given list of names in ascending ordeer
import java.util.Scanner;
public class Alphabetical_Order
{
public static void main(String[] args)
{
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to enter:");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i = 0; i < n; i++)
{
names[i] = s1.nextLine();
}
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j])>0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(names[i] + ",");
}
System.out.print(names[n - 1]);
}
}
31
OUTPUT:
$ javac Alphabetical_Order.java
$ java Alphabetical_Order
32
25. Write a java program to check the compatibility for multiplication, if compatible
multiplies two matrices and find its transpose.
import java.util.Scanner;
class Matrix
{
void matrixMul(int m, int n, int p, int q)
{
int[][] a,b,c,t;
a = new int[m][n];
b = new int[p][q];
c = new int[m][q];
t = new int[q][m];
Scanner s = new Scanner(System.in);
System.out.println("Enter the elements of matrix A: ");
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
a[i][j] = s.nextInt();
}
}
System.out.println("Enter the elements of matrix B: ");
for(int i = 0; i < p; i++)
{
for(int j = 0; j < q; j++)
{
b[i][j] = s.nextInt();
}
}
for(int i = 0; i < m; i++)
{
for(int j = 0; j < q; j++)
{
for(int k = 0; k < n; k++)
{
c[i][j] += a[i][k]*b[k][j];
}
}
}
System.out.println("Elements of result matrix C are: ");
33
for(int i = 0; i < m; i++)
{
for(int j = 0; j < q; j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.print("\n");
}
for(int i = 0; i < q; i++)
{
for(int j = 0; j < m; j++)
{
t[i][j] = c[j][i];
}
}
System.out.println("Elements of transpose matrix T are: ");
for(int i = 0; i < q; i++)
{
for(int j = 0; j < m; j++)
{
System.out.print(t[i][j]+"\t");
}
System.out.print("\n");
}
}
}
class Driver
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter no of rows in first matrix: ");
int m = s.nextInt();
System.out.println("Enter no of columns in first matrix: ");
int n = s.nextInt();
System.out.println("Enter no of rows in second matrix: ");
int p = s.nextInt();
System.out.println("Enter no of columns in second matrix: ");
int q = s.nextInt();
if(n == p)
34
{
Matrix obj = new Matrix();
obj.matrixMul(m,n,p,q);
}
else
{
System.out.println("Matrix multiplication cannot be performed...");
}
}
}
OUTPUT:
Enter no of rows in first matrix:
3
Enter no of columns in first matrix:
3
Enter no of rows in second matrix:
3
Enter no of columns in second matrix:
3
Enter the elements of matrix A:
111
222
333
Enter the elements of matrix B:
123
123
111
Elements of result matrix C are:
3 5 7
6 10 14
9 15 21
Elements of transpose matrix T are:
3 6 9
5 10 15
7 14 21
35
26. Write a java program that illustrates how runtime polymorphism is achieved.
36
Rectangle r = new Rectangle(20,30);
f = t;
f.area();
f = r;
f.area();
}
}
OUTPUT:
37
27. Write a java program to create and demonstrate package
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
Output :
Welcome to package
38
28. Write a java program using StringTokenizer class, which reads a line of
integers and then displays each integer and the sum of all integers.
import java.util.*;
class StringTokenDemo
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.print("Enter a line of numbers: ");
String input = s.next();
StringTokenizer st = new
StringTokenizer(input,"@");
int sum = 0;
while(st.hasMoreTokens())
{
int n = 0;
n = Integer.parseInt(st.nextToken());
System.out.println("Number is: "+n);
sum += n;
}
System.out.println("Sum of the numbers is: "+sum);
}
}
OUTPUT:
Enter a line of numbers: 2@3@1@4@5
Number is: 2
Number is: 3
Number is: 1
Number is: 4
Number is: 5
Sum of the numbers is: 15
39
29. Write a java program that reads a file name from the user and then displays
information about whether the file exists, whether the file is
readable/writable, the type of file and the length of the file in bytes and
display the content using FileInputStream.
import java.io.*;
import javax.swing.*;
class FileDemo
{
public static void main(String args[])
{
String filename = JOptionPane.showInputDialog("Enter filename: ");
File f = new File(filename);
System.out.println("File exists: "+f.exists());
System.out.println("File is readable: "+f.canRead());
System.out.println("File is writable: "+f.canWrite());
System.out.println("Is a directory: "+f.isDirectory());
System.out.println("length of the file: "+f.length()+" bytes");
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream(filename);
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
System.out.println("\nContents of the file are: ");
System.out.println(buff);
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
}
}
OUTPUT:
40
File name: sample.txt
File exists: true
File is readable: true
File is writable: true
Is a directory: false
length of the file: 20 bytes
Contents of the file are:
Hi, welcome to Java.
41
30. Write a java program that displays the number of characters, lines and words in a text
file.
import java.util.*;
import java.io.*;
class Cfile
{
public static void main(String args[])throws IOException
{
int nl=1,nw=0;
char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.nextLine();
FileInputStream f=new FileInputStream(str);
int n=f.available();
for(int i=0;i<n;i++)
{
ch=(char)f.read();
if(ch=='\n')
nl++;
else if(ch==' ')
nw++;
}
System.out.println("\nNumber of lines : "+nl);
System.out.println("\nNumber of words : "+(nl+nw));
System.out.println("\nNumber of characters : "+n)
}
}
OUTPUT:
Enter File name: Sample.txt
Number of lines : 3
Number of words : 3
Number of characters : 26
42
31. Write an Applet program that displays the content of the file.
/*
<applet code="MyApplet" height="300" width="500">
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.io.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
String content = "";
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new
FileInputStream("sample.txt");
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
fis.close();
content = new String(buff);
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
43
{
System.out.println("Cannot read file...");
}
g.drawString(content,20,20);
}
}
OUTPUT:
Contents of sample.txt file:
Hi, welcome to Java.
32. Write a java program that allows the user to draw lines,rectangles and ovals.
44
import java.applet.*;
import java.awt.*;
import javax.swing.*;
public class LinesRectsOvals extends JApplet
{
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.red);
g.drawLine(5,30,350,30);
g.setColor(Color.blue);
g.drawRect(5,40,90,55);
g.fillRect(100,40,90,55);
g.setColor(Color.cyan);
g.fillRoundRect(195,40,90,55,50,50);
g.drawRoundRect(290,40,90,55,20,20);
g.setColor(Color.yellow);
g.draw3DRect(5,100,90,55,true);
g.fill3DRect(100,100,90,55,false);
g.setColor(Color.magenta);
g.drawOval(195,100,90,55);
g.fillOval(290,100,90,55);
}
}
Output:
45
46
33. Write a java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field
to display the result.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
TextField t;
String op2[]={"+","-","*","%","=","C"};
String str1="";
int p=0,q=0;
String oper;
setLayout(new GridLayout(5,4));
t=new TextField(20);
setBackground(Color.pink);
setFont(new Font("Arial",Font.BOLD,20));
int k=0;
47
t.setEditable(false);
t.setBackground(Color.white);
t.setText("0");
for(int i=0;i<10;i++)
b[i]=new Button(""+k);
add(b[i]);
k++;
b[i].setBackground(Color.pink);
b[i].addActionListener(this);
for(int i=0;i<6;i++)
b1[i]=new Button(""+op2[i]);
add(b1[i]);
b1[i].setBackground(Color.pink);
b1[i].addActionListener(this);
add(t);
{
48
String str=ae.getActionCommand();
if(str.equals("+")){
p=Integer.parseInt(t.getText());
oper=str;
t.setText(str1="");
oper=str;
t.setText(str1="");
oper=str;
t.setText(str1="");
oper=str;
t.setText(str1="");
if(oper.equals("+")) {
49
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p+q)));}
else if(oper.equals("-")) {
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p-q))); }
else if(oper.equals("*")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p*q))); }
else if(oper.equals("%")){
q=Integer.parseInt(t.getText());
t.setText(String.valueOf((p%q))); }
t.setText("");
str1="";
t.setText("0");
50
else{ t.setText(str1.concat(str));
str1=t.getText();
OUTPUT:
51
34. Write a java program for handling mouse events.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MouseEvents" width=300 height=100>
</applet>
*/
52
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Down";
repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
sg = "*";
showStatus("Dragging mouse at " + mouseX + ", " + mouseY);
repaint();
}
// Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus("Moving mouse at " + me.getX() + ", " + me.getY());
}
// Display msg in applet window at current X,Y location.
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
53
Output:
54
35. Write a java program to Demonstrating the life cycle of a tread.
class thread implements Runnable
{
public void run()
{
// moving thread2 to timed waiting state
try
{
Thread.sleep(1500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
55
// thread1 created and is currently in the NEW state.
System.out.println("State of thread2 after creating it - "+
thread2.getState());
thread2.start();
try
{
// waiting for thread2 to die
thread2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("State of thread2 when it has finished it's
execution - " +
thread2.getState());
}
}
Output:
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on
it - RUNNABLE
State of thread2 after creating it - NEW
56
State of thread2 after calling .start() method on
it - RUNNABLE
State of thread2 after calling .sleep() method on
it - TIMED_WAITING
State of thread1 while it called join() method on
thread2 -WAITING
State of thread2 when it has finished it's
execution - TERMINATED
57