Lab Report OOP_with_Java
Lab Report OOP_with_Java
(BCS452)
Bachelor of Technology
in
Session: 2023-24
Submitted by:
Submitted to:
Name:
Branch:
Semester: Mohammad Sharique
(Assistant Professor)
Roll No:
INDEX
Write a Program to print the text “Hello World”. Save it with name
1 1
Test.java in your folder.
2 Write a Program to print the area of triangle. Save it with name Area.java in your folder. 1
Write a java Program to convert any decimal number into its binary
6 2
equivalent.
Write a program to create a class Student with data ‘name, city and age’ along with method
7 3
printData to display the data. Create the two objects s1 ,s2 to declare and access the values.
WAP using parameterized constructor with two parameters id and name. While creating the
9 objects obj1 and obj2 passed two arguments so that this constructor gets invoked after 4
creation of obj1 and obj2.
Write a program in JAVA to create a class Bird also declares the different parameterized
11 6
constructor to display the name of Birds.
Write a java program in which you will declare two interface sum and Add inherits these
13 7
interface through class A1 and display their content.
Write a program in java if number is less than 10 and greater than 50 it generate the
22 14
exception out of rang, else it displays the square of number.
Write a program in java to enter the number through command line argument if first and
23 second number is not entered it will generate the exception. Also divide the first number 14
with second number and generate the arithmetic exception.
26 Write a java program in which thread sleep for 5 sec and change the name of thread. 16
Write a java program for multithread in which user thread and thread started from main
27 16
method invoked at a time each thread sleep for 1 sec.
Write a java program for to solve producer consumer problem in which a producer produce
28 17
a value and consumer consume the value before producer generate the next value.
29 Write a java program to create a file and write the text in it and save the file. 19
30 Write a java program to read a file and display the content on screen. 20
1
}
4. Write a java Program to generate a Fibonacci Series.
class FibonacciExample1 {
public static void main(String args[])
{
int nl = 0, n2 = 1, n3, i, count = 10;
System.out.print(nl + " " + n2); //printing 0 and 1
for (i = 2; i < count; ++1) //loop starts from 2 because 0 and 1 are already printed
{
n3 = nl + n2;
System.out.print(" " + n3);
nl = n2;
n2 = n3;
}
}
}
5. Write a java Program to generate a Ladder of number.
import java.util.Scanner;
class Ladder {
public static void main(String arr[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows");
int a = in .nextInt();
for (int 1 = 1; i <= a; i + 4) {
for (int j = 15 j <= 1: j + 4 + )
System.out.print(j);
for (int k = i - 1; k >= 1; k--)
System.out.print(k);
System.out.print("\n");
}
}}
6. Write a java Program to convert any decimal number into its binary equivalent.
public class Convert {
public static void main(String[] args) {
int decimal = 10;
String binary = decimalToBinary(decimal);
2
System.out.printin("Decimal: " + decimal);
System.out.printIn("Binary: " + binary);
}
public static String decimalToBinary(int n) {
int remainder, quotient = n;
String binaryNum = "";
while (quotient > 0) {
remainder = quotient % 2;
binaryNum = Integer.toString(remainder) + binaryNum;
quotient = quotient / 2;
}
return binaryNum;
}
}
7. Write a program to create a class Student with data ‘name, city and age’ along with method
printData to display the data. Create the two objects s1 ,s2 to declare and access the values.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
3
}
}
8. Write a program to create a class Student2 along with two method getData(), printData() to get the
value through argument and display the data in printData. Create the two objects s1 ,s2 to declare
and access the values from class STtest.
class Student2 {
4
Employee(int id, String name)
{
this.emplId = id;
this.empName = name;
}
void info()
{
System.out.printin("Id: " + empId + " Name: " + empName);
}
public static void main(String args[])
{
Employee obj1 = new Employee(10245, "Chaitanya");
Employee obj2 = new Employee(92232, "Negan");
obj1.infoQ;
obj2.infoQ;
}
}
10. Write a program in JAVA to demonstrate the method and constructor overloading.
class Cons {
Int p, q;
public CsQ {}
public Cs(int x, int y) {
P = X;
q = y;
}
Public int add(int i, int j) {
return (i + j);
}
Public int add(int i, int j, int k) {
return (i + j + k);
}
public float add(float f1, float f2) {
return (f1 + f2);
}
public void printDataQ) {
5
System.out.print("p = " + p);
System.out.println(" q = " + q);
}
}
Class ConstructorOverlaoding {
public static void main(String args[]) {
int x = 2, y = 3, z = 4;
Cs c = new CsQ);
Cs cl = new Cs(x, z);
cl.printDataQ);
float m = 7.2 F, n = 5.2 F;
int k = c.add(x, y);
int t = c.add(x, y, z);
float ft = c.add(m, n);
System.out.printin("k = " + k);
System.out.printin("t = "++);
System.out.printin("ft = " + ft);
}
}
11. Write a program in JAVA to create a class Bird also declares the different parameterized
constructor to display the name of Birds.
class Bird {
int age;
String name;
Bird()
{
System.out.println("this is the perrot");
}
Bird(String x)
{
name = x;
System.out.println("this is the " + name);
}
Bird(int y, String z)
{
age = y,
6
name = z;
System.out.println("this is the " + aget + "years\t" + name);
}
public static void main(String arr[]) {
Bird a = new BirdQ);
a.BirdQ;
Bird b = new Bird("maina");
Bird c = new Bird(20, "sparrow");
}
}
12. Write a program in java to generate an abstract class A also class B inherits the class A. Generate
the object for class B and display the text “call me from B”.
abstract class A
{
abstract void call();
}
class B extends A
{
public void call() {
System.out.println("call me from B");
}
public static void main(String arr[]) {
B b = new BO;
b.callQ;
}
}
13. Write a java program in which you will declare two interface sum and Add inherits these interface
through class A1 and display their content.
interface sum {
Int sm = 90;
Void sumaQ);
}
Interface add {
int ad = 89;
voidadda();
}
7
class Al implements add, sum {
public void suma()
{
System.out.println(+sm);
}
public void adda()
{
System.out.println(+ad);
}
public static void main(String arr[]) {
Al n = new AlQ;
n.adda();
n.suma();
}
}
14. Java program to illustrate the concept of single inheritance.
import java.util.*;
import java.lang.*;
import java.io.*;
class One
{
Public void print1() {
System.out.println("JIT");
}
}
Class Two extends One
{
Public void print2()
{
System.out.println("CSE");
}
}
// Driver class
Public class Main {
Public static void main(String[] args) {
8
Two obj = new Two(Q);
obj.print1();
obj.print2();
}
}
15. Java program to illustrate the concept of Multilevel inheritance.
import java.util.*;
import java.lang.*;
import java.io.*;
Class One
{
Public void print1() {
System.out.println("JIT");
}
}
Class Two extends One
{
Public void print2() {
System.out.println("CSE");
}
}
Class Three extends Two
{
Public void print1() {
System.out.println("JETGI");
}
}
// Drived class
Public classMain
{
Public static void main(String[] args) {
three obj = new three();
obj.print_geek(Q);
obj.print_forQ;
obj.print_geek(Q);
}
9
}
16. A Simple Java program to demonstrate method overriding in java.
Class Parent
{
Void show() {
System.out.println("Parent's show()");
}
}
Class Child extends Parent
{ // This method overrides showQ of Parent @Override
Void show()
{
System.out.println("Child's show()");
}
}
// Driver class
Class Main
{
Public static void main(String[] args)
{
// If a Parent type reference refers to a Parent object, then Parent's show() is called
Parent obj1 = new Parent();
objl.show();
// If a Parent type reference refers to a Child object Child's show() is called. This is called RUN TIME
POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}
17. Super Keyword in Java Use of super with variables.
Class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
Class Car extends Vehicle
10
{
int maxSpeed = 180;
Void display() {
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
classTest
{
Public static void main(String[] args) {
Car small = newCar();
small.display();
}
}
11
// compare every element with current max
for (i = 1; i < arr.length; i++)
if (arr[i] > max)
max = arrt[i];
return max;
}
// Driver method
public static void main(String[] args) {
System.out.println("Largest in given array is " + largest());
}
}
19. Implementation of the sort() function across different scenarios of the Arrays class.
import java.util.Arrays;
class Demo {
public static void main(String args[]) {
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num: arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.printIn("\nThe sorted array is: ");
for (int num: arr) {
System.out.print(num + "'");
}
}
}
20. Java program for addition of two matrices.
import java.io.*;
class GFG {
// Function to print Matrix
static void printMatrix(int M[][],int rowSize, int colSize) {
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");
System.out.println();
12
}
}
// Function to add the two matrices
// and store in matrix C
static int[][] add(int A[][], int B[][], int size) {
int i, j;
int C[][] = new int[size][size];
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
C[i][j] = A[i][j] + B[i][j];
return C;
}
// Driver code
public static void main(String[] args) {
int size = 4;
int A[][] = { { 1, 1, 1, 1}
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices A
System.out.println("\nMatrix A:");
printMatrix(A, size, size);
int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } }; };
// Print the matrices B
System.out.println("\nMatrix B:");
printMatrix(B, size, size);
// Add the two matrices
int C[][] = add(A, B, size);
// Print the result
System.out.println("\nResultant Matrix:");
printMatrix(C, size, size);
}
}
13
21. Java program to reverse a word.
import java.io.*;
import java.util.Scanner;
class GFG {
public static void main(String[] args) {
String str = "Geeks", nstr = "";
char ch;
System.out.print("Original word: ");
System.out.println("Geeks"); //Example word
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i); //extracts each character
nstr = ch + nstr; //adds each character in front of
//the existing string
}
System.out.println("Reversed word: " + nstr);
}
}
22. Write a program in java if number is less than 10 and greater than 50 it generate the exception out
of rang, else it displays the square of number.
Class CustomTest {
public static void main(String arr[]) {
try {
int a = Integer.parseInt(arr[0]);
if (a50) throw (new outofRangeException("valid range is 10 to 50")); {
int s = a * a;
System.out.println("Square is:" + s);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
23. Write a program in java to enter the number through command line argument if first and second
number is not entered it will generate the exception. Also divide the first number with second
number and generate the arithmetic exception.
class Divide2 {
public static void main(String arr[]) {
try {
if (arr.length < 2)
14
throw (new Exception("two argument must be provided"));
int a = Integer.parseInt(arr[0]);
int
b = Integer.parseInt(arr[1]);
if (b == 0)
throw (new Exception("second argument should be non
zero"));
int c = a / b;
System.out.println("result:" + c);
} catch (Exception e) {
System.out.println(e);
}
}
}
24. Example of package that import the packagename.*
//save A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
25. Example of package by import fully qualified name.
//save by A.java
package pack;
public class A {
public void msg() {
15
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output: Hello
26. Write a java program in which thread sleep for 5 sec and change the name of thread.
import java.lang.*;
Class ThreadTest extends Thread {
static {
Thread t = Thread.currentThread();
//Thread t=new Thread.currentThread();
System.out.println("thread test is loaded by" + t.getName() +
"thread");
t.setName("vishal");
System.out.println("changed the name of thread ");
System.out.println("suspending thread
for 5 sec "); try {
Thread.sleep(5000);
} catch (Exception ex) {}
}
public static void main(String arr[]) {
Thread t = Thread.currentThread();
System.out.println("main() is invoked in" + t.getName() + "thread...");
}
}
27. Write a java program for multithread in which user thread and thread started from main method
invoked at a time each thread sleep for 1 sec.
Class UserThread extends Thread {
public void run() {
16
Thread t = Thread.currentThread();
System.out.println("run() is invoked in" + t.getName() +
"thread...");
for (int i = 1; i <= 10; i++) {
System.out.println("run:" + i);
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
System.out.println("run() is completed");
}
}
classMultiThread {
public static void main(String arr[]) {
System.out.println("main() started creating an object of user Thread. ");
UserThread t = new UserThread();
System.out.println("directly invoking run() of
user thread "); t.run();
System.out.println("control back in main() "); System.out.println("launching new thread for run() of
user thread. "); t.start();
for (int i = 10; i > 0; i--) {
System.out.println("
main: "+i); try {
Thread.sleep(1000);
} catch (Exception e) {}
}
System.out.println("main() completed");
}
}
28. Write a java program for to solve producer consumer problem in which a producer produce a
value and consumer consume the value before producer generate the next value.
class Buffer {
int value;
boolean produced = false;
public synchronized void produce(int x) {
if (produced) {
17
System.out.println("producer enter monitor out of turn..suspend. ");
try {
wait();
} catch (Exception e) {}
}
value = x;
System.out.println(value + "is
produced "); produced=true;
notify();
}
public synchronized void consume() {
if (!produced) {
System.out.println("consumer enterd the monitor out of turn,suspend.................");
try {
wait();
} catch (Exception e) {}
}
System.out.println(value + "is consumed");
produced = false;
notify();
}
}
class Producer extends Thread {
Buffer buffer;
public Producer(Buffer b) {
buffer = b;
}
Public void run() {
{
System.out.println("producer started ,producing value.....................");
for (int i = 1; 1 <= 10; i++)
buffer.produce(i);
}
}
class Consumer extends Thread {
Buffer buffer;
18
public Consumer(Buffer b) {
buffer = b;
}
public void run() {
System.out.println("consumer started,consuming value.................");
for (int i = 1; i <= 10; i +
+) buffer.consme();
}
}
class PC1 {
public static void main(String arr[]) {
Buffer b = new Buffer();
Producer p = new Producer(b);
Consumer c = new Consumer(b);
p.start();
c.start();
}
}
29. Write a java program to create a file and write the text in it and save the file.
import java.io.*;
Class CreateFile {
public static void main(String arr[]) {
if (arr.length < 1) {
try
System.out.println("usage:javacreatefile file name");
System.exit(0);
}{
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
PrintStreamfos = new PrintStream(new FileOutputStream(arr[0]));
System.out.println("Enter text end
to save ");
PrintStream temp = System.out; System.setOut(fos); do {
String str = b.readLine();
if (str.equalsIgnoreCase("e
nd "));
System.out.pri ntln(str); brea k;
19
}
while (true); System.setOut(te mp); fos.close(); b.close(); System.out.println("successfully
created");
}
catch (Exception ex) {
System.out.println(ex);
}}
}
30. Write a java program to read a file and display the content on screen.
import java.io.*;
class input
{
public static void main(String arr[])
{
try
{
FileInputStream fis=new FileInputStream("J.text");
int a=fis.read();
System.out.println(a);
}
catch(IOException e)
{
}
}
}
20
//Traversing list through Iterator
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
32. Write a java program to create a stack collection.
import java.util.*;
public class TestJavaCollection4 {
public static void main(String args[]) {
Stack < String > stack = new Stack < String > ();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator < String > itr = stack.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
21
System.out.println("head:" + queue.peek());
System.out.println("itera琀椀ng the queue elements:");
Iterator itr = queue.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("a昀琀er removing two elements:");
Iterator < String > itr2 = queue.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}
34. Write a java program to create a Hash set collection.
import java.util.*;
class HashSet1 {
public static void main(String args[]) {
//Creating HashSet and adding elements
HashSet < String > set = new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator < String > i = set.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
35. Write a java program to create a Tree set collection.
import java.util.*;
class TreeSet1 {
public static void main(String args[]) {
22
//Creating and adding elements
TreeSet < String > al = new TreeSet < String > ();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
//Traversing elements
Iterator < String > itr = al.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
23